How do map, filter, and reduce work in JavaScript?
map transforms each element, filter keeps elements that pass a test, and reduce accumulates all elements into a single value.
JavaScript
Overview
`map`, `filter`, and `reduce` are the core array methods for functional-style data transformation. They are pure and do not mutate the original array. Mastering them replaces most `for` loop patterns with cleaner, more readable code.
Key Points
- •`map(fn)` returns a new array of the same length with each element transformed by `fn`.
- •`filter(fn)` returns a new array containing only elements for which `fn` returns `true`.
- •`reduce(fn, initial)` processes each element left-to-right, accumulating a single result.
- •All three accept a callback with `(element, index, array)` arguments.
- •Chain them: `arr.filter(...).map(...)` but for performance-critical code, a single `reduce` may be faster.
Examples
map: transform each element
javascriptconst prices = [10, 20, 30];
const doubled = prices.map(p => p * 2);
// [20, 40, 60]
const users = [{ name: 'Alice' }, { name: 'Bob' }];
const names = users.map(u => u.name);
// ['Alice', 'Bob']filter: keep elements that pass a test
javascriptconst numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6]
const adults = users.filter(u => u.age >= 18);reduce: accumulate into a single value
javascriptconst nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, n) => acc + n, 0);
// 10
// Group items by category
const grouped = items.reduce((acc, item) => {
(acc[item.category] ??= []).push(item);
return acc;
}, {});Chaining all three
javascriptconst total = orders
.filter(o => o.status === 'paid') // keep paid orders
.map(o => o.amount) // extract amounts
.reduce((sum, amount) => sum + amount, 0); // sum them upPro Tip
`reduce` is the most powerful but also the hardest to read. Prefer `filter` + `map` chaining when the intent is clearer, and reserve `reduce` for cases where a single-pass accumulation is genuinely needed.