Arrays and Objects
map, filter, reduce, destructuring and spread for everyday data work.
What you will learn
- Transform arrays without loops
- Destructure objects
- Copy with spread
Arrays hold ordered lists and objects hold named properties. Almost all real JavaScript is transforming these two shapes. Learning the array methods well means you rarely need a manual for loop.
const nums = [1, 2, 3];
nums.push(4); // add to end
nums.unshift(0); // add to start
console.log(nums, nums.length, nums.at(-1));
console.log(nums.includes(3), nums.indexOf(3));[ 0, 1, 2, 3, 4 ] 5 4 true 3
map, filter, reduce
map transforms every item, filter keeps some, and reduce folds the list into one value. None of them change the original array; they return new ones, so they chain nicely.
const prices = [10, 25, 40, 5];
const withTax = prices.map((p) => p * 1.2);
const big = prices.filter((p) => p > 9);
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(withTax);
console.log(big, total);[ 12, 30, 48, 6 ] [ 10, 25, 40 ] 80
Also useful: find (first match), some / every (yes/no checks), sort and flat. Beware that sort() converts to strings by default and mutates the array; pass a comparer for numbers: nums.sort((a, b) => a - b).
const user = { name: "Ada", age: 36, tags: ["dev"] };
user.role = "admin";
console.log(user.name, user["age"]);
console.log(Object.keys(user));
console.log(Object.entries(user).length);Ada 36 [ 'name', 'age', 'tags', 'role' ] 4
Destructuring and spread
Destructuring unpacks values into variables; the spread operator ... copies or merges. Together they give you concise, immutable-style updates that React relies on.
const { name, ...rest } = user;
const [first, second] = [10, 20, 30];
const updated = { ...user, age: 37 };
const merged = [...[1, 2], ...[3]];
console.log(name, first, second, updated.age, merged);Ada 10 20 37 [ 1, 2, 3 ]
Spread copies only the top level. Nested objects are still shared. Use structuredClone(obj) for a deep copy.
const words = ["apple", "avocado", "banana"];
const byLetter = words.reduce((acc, w) => {
(acc[w[0]] ??= []).push(w);
return acc;
}, {});
console.log(byLetter);{ a: [ 'apple', 'avocado' ], b: [ 'banana' ] }Try it yourself
Given an array of user objects with name and age, produce an array of the names of users aged 18 or over, sorted alphabetically.
Show solution
const users = [{ name: "Zed", age: 20 }, { name: "Amy", age: 15 }, { name: "Bob", age: 30 }];
const adults = users
.filter((u) => u.age >= 18)
.map((u) => u.name)
.sort();
console.log(adults); // [ 'Bob', 'Zed' ]