`map` / `filter` / `reduce`
map transforms each element, filter keeps elements that pass a test, and reduce folds the list into a single value. They are the standard functional trio on Array.prototype.
Detailed Explanation
These three methods walk an array and call a function you supply. They do not mutate the original array (the callback still can, if you write it that way). They skip holes, unlike spread.
map(fn) returns a new array of the same .length. Each index holds fn(element, index, array). Use it when the output is "one item per input item": prices to tax-inclusive prices, users to emails. If you do not use the return value, you wanted forEach.
filter(fn) returns a new array of the elements for which fn is truthy. Indexes are not preserved; survivors pack left. Use it when the output is "some of the input". Combining map then filter is common; flatMap can replace map-plus-empty-array.
reduce(fn, initial) calls fn(acc, element, index, array) left to right and returns the last acc. The initial value is the starting acc. If you omit it, the first present element is the start and the walk begins at the next one. An empty array with no initial value throws TypeError. Always pass an initial value: 0 for sums, [] for building arrays, {} or new Map() for grouping.
reduceRight walks from the end. flatMap(fn) is map(fn) then flat(1), which is the right tool when each element becomes zero or more outputs.
Callbacks receive (item, index, array). Using index in map is fine. Using array to look at neighbours is fine and makes the function less reusable. Do not mutate array inside the callback; the walk is specified against the original length, and mutations are confusing.
What it costs you: intermediate arrays. xs.filter(ok).map(fn) allocates twice. A single reduce or a for can allocate once. For a few hundred items this is noise. For a hot path, fuse the passes. Also, reduce is easy to overuse: a for...of that builds a Map is often easier to read than a 15-line reducer.
Reach for map/filter for new arrays. Reach for reduce for a scalar or a single structure. Reach for flatMap when each item can disappear or expand. Reach for a loop when you need break, await, or fewer allocations.
Code Examples
const cart = [
{ name: "book", price: 10 },
{ name: "pen", price: 2 },
{ name: "desk", price: 80 },
];
const names = cart.map((item) => item.name);
console.log(names); // => [ 'book', 'pen', 'desk' ]
const cheap = cart.filter((item) => item.price < 20);
console.log(cheap.map((item) => item.name)); // => [ 'book', 'pen' ]
const total = cart.reduce((sum, item) => sum + item.price, 0);
console.log(total); // => 92const grouped = cart.reduce((map, item) => {
const bucket = item.price < 20 ? "cheap" : "spend";
const list = map.get(bucket) ?? [];
list.push(item.name);
map.set(bucket, list);
return map;
}, new Map());
console.log(grouped.get("cheap")); // => [ 'book', 'pen' ]try {
[].reduce((a, b) => a + b);
} catch (err) {
console.log(err.name); // => TypeError
}
console.log([].reduce((a, b) => a + b, 0)); // => 0Common Gotchas
`reduce` on `[]` without an initial value throws
pass `0`, `[]`, or another identity.
`map` is not `forEach`
throwing away the result wastes an array. Use `forEach` or a `for` for side effects.
Holes are skipped
`[1, , 3].map(x => x * 2)` keeps a hole at index 1. Fill the array first if you need a value per index.
The callback's third argument is the original array
mutating it mid-pass is specified but hostile to readers. Do not.