map, filter and reduce
Modern JavaScript processes arrays with methods that take callbacks, instead of hand-written loops.
map: transform every item
JavaScript
const prices = [100, 250, 80];
const withTax = prices.map((p) => p * 1.18);
console.log(withTax);
const names = ["asha", "leo"];
console.log(names.map((n) => n[0].toUpperCase() + n.slice(1)));map returns a new array of the same length. The original is unchanged.
filter: keep some items
JavaScript
const scores = [72, 95, 58, 88, 41];
const passed = scores.filter((s) => s >= 60);
console.log(passed);reduce: combine into one value
reduce walks the array carrying an accumulator:
JavaScript
const prices = [100, 250, 80];
const total = prices.reduce((sum, p) => sum + p, 0); // 0 is the starting value
console.log(total);
const words = ["map", "filter", "reduce"];
const longest = words.reduce((best, w) => (w.length > best.length ? w : best));
console.log(longest);Finding
JavaScript
const users = [
{ id: 1, name: "Asha", admin: false },
{ id: 2, name: "Leo", admin: true },
{ id: 3, name: "Mei", admin: false },
];
console.log(users.find((u) => u.id === 2)); // first match, or undefined
console.log(users.findIndex((u) => u.name === "Mei"));
console.log(users.some((u) => u.admin)); // at least one?
console.log(users.every((u) => u.name.length >= 3)); // all?Chaining
Because each method returns an array, you can chain them into a pipeline that reads like a description:
JavaScript
const orders = [
{ product: "Keyboard", price: 89.99, qty: 1, status: "delivered" },
{ product: "Mouse", price: 24.5, qty: 3, status: "delivered" },
{ product: "Monitor", price: 279, qty: 1, status: "cancelled" },
{ product: "Lamp", price: 27.75, qty: 2, status: "delivered" },
];
const revenue = orders
.filter((o) => o.status === "delivered")
.map((o) => o.price * o.qty)
.reduce((sum, v) => sum + v, 0);
console.log(revenue.toFixed(2));Others worth knowing
JavaScript
const nested = [[1, 2], [3, [4, 5]]];
console.log(nested.flat(2));
console.log([3, 1, 2].includes(2));
console.log(Array.from({ length: 5 }, (_, i) => i * i));
console.log([1, 2, 3, 4].findLast((n) => n % 2 === 1));Finished this lesson?Mark it complete to earn +20 XP and move your progress on.