map, filter and reduce
Overview
Three methods cover most of what loops are used for, and they never change the original array:
map— make a new array by transforming every item.filter— make a new array by keeping some items.reduce— combine all the items into a single value.
Compare the loop version with the method version of the same job:
// Loop
const names = [];
for (const user of users) {
if (user.active) {
names.push(user.name);
}
}
// Methods
const names = users.filter((u) => u.active).map((u) => u.name);The method version says what you want, not how to build it step by step.
map — transform each item
const prices = [100, 250, 40];
const withTax = prices.map((p) => p * 1.18); // [118, 295, 47.2]
const titles = lessons.map((l) => l.title);The callback receives each item (plus its index and the array) and returns the new item. The result always has the same number of items as the original.
map is ideal for reshaping objects:
const users = [
{ first: 'Asha', last: 'Rao', age: 30 },
{ first: 'Ravi', last: 'Kumar', age: 25 },
];
const cards = users.map((u) => ({
name: `${u.first} ${u.last}`,
isAdult: u.age >= 18,
}));
// [{ name: 'Asha Rao', isAdult: true }, { name: 'Ravi Kumar', isAdult: true }]And for turning data into HTML strings:
const html = `<ul>${titles.map((t) => `<li>${t}</li>`).join('')}</ul>`;Forgetting
return. With a block body,items.map((x) => { x * 2 })returnsundefinedfor every item. Either drop the braces or addreturn.
filter — keep some items
const cheap = prices.filter((p) => p < 150); // [100, 40]The callback returns true to keep an item, false to drop it. The kept items are the same items (not copies), in their original order.
Common filters:
const active = users.filter((u) => u.active);
const withoutAsha = users.filter((u) => u.first !== 'Asha'); // remove by value
const nonEmpty = ['a', '', 'b', null].filter(Boolean); // ['a', 'b'] — drop falsy values
const unique = [1, 2, 2, 3].filter((n, i, arr) => arr.indexOf(n) === i); // [1, 2, 3]filter(Boolean) passes each item to the Boolean function, which returns false for falsy values — a neat trick to remove blanks.
reduce — combine into one value
reduce passes a running total (the accumulator) along with each item:
const total = prices.reduce((sum, p) => sum + p, 0); // 390The callback’s return value becomes the accumulator for the next item. When all items are processed, the final accumulator is the result:
The 0 is the starting value. Leave it out and reduce uses the first item instead — which breaks on empty arrays (TypeError: Reduce of empty array with no initial value).
The accumulator can be anything — a number, a string, an object, an array:
// Largest value
const max = prices.reduce((best, p) => (p > best ? p : best), -Infinity);
// Count by category
const counts = products.reduce((acc, p) => {
acc[p.category] = (acc[p.category] ?? 0) + 1;
return acc;
}, {});
// { fruit: 3, dairy: 2 }For grouping, modern JavaScript also has Object.groupBy(products, (p) => p.category), which returns the items grouped into arrays.
Chaining
Because each returns a new array (or value), you can chain them:
const total = cart
.filter((item) => item.inStock)
.map((item) => item.price * item.qty)
.reduce((sum, n) => sum + n, 0);Read it top to bottom: keep the in-stock items, turn each into its line total, add them up. Putting each step on its own line keeps long chains readable.
Readability first. If a
reducegets hard to follow, a plainfor…ofloop is perfectly fine.
Performance
Each step in a chain loops over the array once. For everyday arrays (hundreds or thousands of items) that’s not worth thinking about. Only for very large data, or code that runs many times a second, might you combine steps into a single loop.
Related helpers
flat() flattens nested arrays, and flatMap() maps and flattens in one step.
[[1, 2], [3], [4, 5]].flat(); // [1, 2, 3, 4, 5]
[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]
const sentences = ['hello world', 'good morning'];
sentences.flatMap((s) => s.split(' ')); // ['hello', 'world', 'good', 'morning']flatMap can also filter and map at once, by returning an empty array to drop an item:
const evensDoubled = [1, 2, 3, 4].flatMap((n) => (n % 2 === 0 ? [n * 2] : []));
// [4, 8]Quick reference
| Method | Callback returns | Result |
|---|---|---|
map |
the new item | array, same length |
filter |
true / false |
array, same or fewer items |
reduce |
the next accumulator | any single value |
flatMap |
an array (or item) | flattened array |
forEach |
nothing | undefined |
Total minutes of unfinished lessons
Use filter and reduce to add up minutes for lessons where done is false. Then use map to make an array of titles in upper case.
const lessons = [
{ title: 'Loops', minutes: 6, done: true },
{ title: 'Closures', minutes: 9, done: false },
{ title: 'Promises', minutes: 11, done: false },
];const remaining = lessons
.filter((l) => !l.done)
.reduce((total, l) => total + l.minutes, 0); // 20
const shouting = lessons.map((l) => l.title.toUpperCase());
// ['LOOPS', 'CLOSURES', 'PROMISES']Summary
maptransforms every item and returns a new array of the same length.filterkeeps the items whose callback returns true.reducecombines all items into one value; always give it a starting value.- None of them change the original array, so they chain neatly.
- Use
flatMapto map and flatten, and plain loops when a chain gets hard to read.