map, filter and reduce

Topic 3 of 4 in Arrays7 min readBeginnerFree course

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.

Starting from prices [100, 250, 40]: map(p => p * 1.18) gives [118, 295, 47.2], the same length with every item changed; filter(p => p < 150) gives [100, 40], fewer items unchanged; reduce((sum, p) => sum + p, 0) gives one value, 390.

Compare the loop version with the method version of the same job:

JavaScript
// 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

JavaScript
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:

JavaScript
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:

JavaScript
const html = `<ul>${titles.map((t) => `<li>${t}</li>`).join('')}</ul>`;

Forgetting return. With a block body, items.map((x) => { x * 2 }) returns undefined for every item. Either drop the braces or add return.

filter — keep some items

JavaScript
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:

JavaScript
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:

JavaScript
const total = prices.reduce((sum, p) => sum + p, 0); // 390

The callback’s return value becomes the accumulator for the next item. When all items are processed, the final accumulator is the result:

prices.reduce((sum, p) => sum + p, 0) with prices [100, 250, 40]: call 1 has sum 0 and p 100 and returns 100; call 2 has sum 100 and p 250 and returns 350; call 3 has sum 350 and p 40 and returns 390, 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:

JavaScript
// 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:

JavaScript
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 reduce gets hard to follow, a plain for…of loop 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.

flat() flattens nested arrays, and flatMap() maps and flattens in one step.

JavaScript
[[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:

JavaScript
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
Exercise

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.

JavaScript
const lessons = [
  { title: 'Loops', minutes: 6, done: true },
  { title: 'Closures', minutes: 9, done: false },
  { title: 'Promises', minutes: 11, done: false },
];

Summary

  • map transforms every item and returns a new array of the same length.
  • filter keeps the items whose callback returns true.
  • reduce combines all items into one value; always give it a starting value.
  • None of them change the original array, so they chain neatly.
  • Use flatMap to map and flatten, and plain loops when a chain gets hard to read.