Skip to the content

Lesson 60 of 296

map, filter and reduce

What you will learn

  • What each method does
  • The callback and its parameters
  • How reduce works, step by step
  • Why the starting value of reduce matters
  • Chaining methods together
  • Grouping data with reduce and Object.groupBy
On this page

Why these methods matter

These three methods are used constantly in modern JavaScript and React, and "implement your own map, filter and reduce" is a common interview task (Part 6). They do not change the original array.

map: transform every item

map calls a function for each item and returns a new array of the results. The new array always has the same length.

const prices = [100, 250, 400];
const withVat = prices.map((p) => p * 1.2);       [120, 300, 480]

const users = [{ name: "Sam" }, { name: "Ali" }];
const names = users.map((u) => u.name);           ["Sam", "Ali"]

The callback receives three arguments: (item, index, array). Usually only the first is needed.

["a", "b"].map((letter, i) => `${i}: ${letter}`)     ["0: a", "1: b"]

Mistake: forgetting to return:

prices.map((p) => { p * 2; })       [undefined, undefined, undefined]

With braces, you must write return.

filter: keep some items

filter calls a function for each item and keeps the items where the function returns a truthy value. The new array can be shorter.

const scores = [45, 82, 67, 91, 30];
const passed = scores.filter((s) => s >= 50);       [82, 67, 91]

const active = users.filter((u) => u.isActive);

reduce: combine everything into one value

reduce goes through the array and builds one result: a total, an object, a string, even another array.

const numbers = [5, 10, 15];
const total = numbers.reduce((acc, n) => acc + n, 0);      30

The callback gets:

  • acc (the accumulator): the result so far.
  • n: the current item.

The second argument to reduce (0 here) is the starting value of the accumulator.

Step by step:

Stepacc (before)nacc + n (becomes new acc)
1055
251015
3151530

The final accumulator, 30, is returned.

Always give a starting value

Without a starting value, reduce uses the first item as the starting accumulator and begins from the second item. This causes two problems:

[].reduce((a, b) => a + b);             TypeError: Reduce of empty array with no initial value
[].reduce((a, b) => a + b, 0);          0

And with arrays of objects, the first "accumulator" is an object, not a number:

const basket = [{ price: 5 }, { price: 7 }];
basket.reduce((sum, item) => sum + item.price);       "[object Object]7"
basket.reduce((sum, item) => sum + item.price, 0);    12

reduce into an object: counting

const fruits = ["apple", "pear", "apple", "kiwi", "apple"];

const counts = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] ?? 0) + 1;
  return acc;
}, {});

Result: { apple: 3, pear: 1, kiwi: 1 }. Always return acc from the callback.

Grouping records by a key

const orders = [
  { id: 1, status: "paid" },
  { id: 2, status: "pending" },
  { id: 3, status: "paid" }
];

const byStatus = orders.reduce((groups, order) => {
  const key = order.status;
  if (!groups[key]) groups[key] = [];
  groups[key].push(order);
  return groups;
}, {});

Result:

{
  paid: [{ id: 1, ... }, { id: 3, ... }],
  pending: [{ id: 2, ... }]
}

Modern JavaScript has a built-in for this (ES2024, supported in current browsers and Node.js 21+):

const byStatus = Object.groupBy(orders, (order) => order.status);

Map.groupBy does the same but returns a Map (Lesson 64). Interviewers may still ask you to write it with reduce.

Chaining

Because map and filter return arrays, you can chain them:

const totalOfPaidOrdersPence = orders
  .filter((o) => o.status === "paid")
  .map((o) => o.amountPence)
  .reduce((sum, amount) => sum + amount, 0);

Each step is simple and readable. With very large arrays, chaining loops over the data several times; a single loop or a single reduce can be faster. For normal amounts of data, readability wins.

Which method?

GoalMethod
Change every item into something elsemap
Keep only some itemsfilter
Turn the array into one value or a different shapereduce
Just do something for each item (log, save)forEach or for...of
Find one itemfind (Lesson 61)

Do not use map when you do not use the returned array; use forEach or for...of instead.

Common mistakes

  • No return inside braces.
  • No starting value in reduce.
  • Forgetting to return acc in reduce.
  • Using map just to loop.
  • Expecting them to change the original array.

How to say it in an interview

"map transforms each element and returns a new array of the same length. filter returns a new array with the elements whose callback returns truthy. reduce folds the array into a single value using an accumulator; I always pass an initial value, because without one an empty array throws and the first element becomes the accumulator. None of them mutate the original. For grouping I can use reduce, or Object.groupBy in modern environments."

Key words

WordMeaning
mapCreates a new array by transforming each item
filterCreates a new array with only matching items
reduceCombines all items into one value
AccumulatorThe running result inside reduce
Initial valueThe starting accumulator for reduce
ChainingCalling one method straight after another
Higher-order functionA function that takes or returns another function

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.