JavaScript, Refreshed
Arrays & objects
Lesson 3 of 5
What you'll learn
- Reach for
map,filter, andreduceinstead of manual loops - Pull values out of arrays and objects with destructuring
- Copy and merge with the spread operator
Most data work is transformation: take a collection and produce a new one. Three array methods cover the vast majority of cases. map transforms each item one-to-one. filter keeps the items that pass a test. reduce folds the whole array down into a single accumulated value — and it's the most general of the three.
const nums = [1, 2, 3, 4];
nums.map((n) => n * 2); // [2, 4, 6, 8]
nums.filter((n) => n % 2 === 0); // [2, 4]
nums.reduce((sum, n) => sum + n, 0); // 10
Destructuring
Destructuring unpacks values into variables by position (arrays) or by key (objects). It makes function signatures and assignments read like the shape of the data.
const [first, second] = ["a", "b"]; // first="a", second="b"
const { name, age } = { name: "Ada", age: 36 };
function greet({ name }) { // destructure a parameter
return "Hi " + name;
}
Spread
The spread operator (...) expands an array or object inline — handy for copying, merging, and combining without mutating the originals.
const base = { theme: "dark" };
const next = { ...base, theme: "light", lang: "en" }; // new object
const combined = [...[1, 2], ...[3, 4]]; // [1, 2, 3, 4]
reduce builds any shape
reduce isn't only for sums. Start with an empty object or array as the accumulator and you can group, index, or restructure data in a single pass.
The challenge uses reduce to group people by their role into an object of arrays — a pattern you'll write constantly.
Run it. reduce folds the array into a grouped object: each role maps to the names that have it.
Next: how JavaScript handles work that doesn't finish right away.
Sign in to save your progress across devices.