Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 156 ยท Arrays

map, filter, reduce and forEach

Transform arrays with map, pick items with filter, combine them with reduce and run side effects with forEach. Includes chaining and common mistakes.

Most work with arrays falls into a few patterns. You transform every item (prices to formatted labels), keep only some items (orders that shipped), combine all items into one value (a total), or simply do something with each item (log it, draw it). You could write a for loop for each of these, and you'd write nearly the same loop every time.

JavaScript's array methods name these patterns: map, filter, reduce and forEach. Each takes a callback, a function that is called once per item (you met callbacks in Higher-Order Functions). Code written with them is shorter, says what it does instead of how, and can be chained into readable pipelines. Except for forEach, they also never change the original array.

The callback signature

All four methods call your function with the same three arguments:

JavaScript
array.map((item, index, array) => { /* ... */ });
  • item โ€” the current value
  • index โ€” its position
  • array โ€” the whole array (rarely needed)

You almost always use just the first, sometimes the second. Name them for what they hold: price, user, word, not x.

forEach: do something with each item

forEach runs the callback for each item and returns undefined. Use it for side effects: logging, updating the page, sending data somewhere.

JS forEach

Press Run (or Ctrl + Enter) to see the console output here.

No output.

forEach is a close cousin of for...of. A few differences matter:

  • You can't stop a forEach early. break is a syntax error inside the callback, and return only ends the current call. If you need to stop, use a for...of loop or a method like some() or find().
  • await inside a forEach callback does not pause the loop. For async work, use for...of (see async and await).

If you're building a new array inside forEach with push, that's a sign you want map or filter instead.

map: transform every item

map calls the callback for each item and collects the return values into a new array of the same length:

JS map

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output always has one item per input item. If you want fewer items, you need filter; if you want one item to become several, look at flatMap in Array Recipes.

Don't forget to return. With curly braces, an arrow function needs an explicit return. prices.map((p) => { p * 2 }) gives [undefined, undefined, undefined]. And to return an object literal from a short arrow, wrap it in parentheses: users.map((u) => ({ id: u.id })). See Arrow Functions.

filter: keep some items

filter calls the callback for each item and keeps the items for which it returns a truthy value. The result is a new array with the same or fewer items, unchanged:

JS filter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

filter(Boolean) is a well-known shortcut. Boolean is a function that returns true for truthy values, so it drops "", null, undefined, 0, NaN and false. Be careful if 0 is a value you want to keep.

The callback is called a predicate: a function that answers yes or no. Write it so it reads like a question: isShipped, isAdult, hasEmail.

reduce: combine everything into one value

reduce is the most general of the four. It walks through the array carrying an accumulator, a running result. On each step, the callback receives the accumulator and the current item, and whatever it returns becomes the accumulator for the next step. The final accumulator is the result:

JavaScript
array.reduce((accumulator, item) => newAccumulator, initialValue);
JS reduce step by step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the first example's log line by line: the accumulator starts at 0 (the initial value), becomes 12, then 17, then 47.

Always pass an initial value. Without one, reduce uses the first item as the starting accumulator and begins at the second item. That works for simple sums, but it throws a TypeError on an empty array, and it breaks when the result is a different type than the items (like the tally object above).

reduce can do anything, which is also its weakness. A reduce that builds an array is usually clearer as map or filter, and one that just loops for side effects should be forEach or for...of. Use it for what it's best at: sums, counts, minimums and maximums, and grouping. (For grouping, modern JavaScript also has Object.groupBy(), covered in Array Recipes.)

Chaining

Because map and filter return arrays, you can call another method on the result right away. Each step reads like a sentence:

JS A pipeline

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Put each step on its own line, starting with the dot. That keeps long chains readable and makes it easy to comment out a step while debugging.

Each step creates a new intermediate array. For everyday data (hundreds or thousands of items) this costs nothing noticeable, and the readability is worth it. If profiling ever shows a hot spot with very large arrays, you can merge steps into a single reduce or loop.

Pitfalls

A few mistakes come up again and again:

  • Using map for side effects. items.map((i) => console.log(i)) works but builds an array of undefined that nobody uses. Use forEach.
  • Mutating inside map. users.map((u) => { u.active = true; return u; }) changes the original objects. Return new ones instead: users.map((u) => ({ ...u, active: true })) (see Spread and Rest).
  • Passing functions with extra parameters. ["1", "2", "3"].map(parseInt) gives [1, NaN, NaN], because map passes the index as parseInt's second argument (the radix). Write .map((s) => parseInt(s, 10)) or .map(Number).
  • Forgetting the initial value in reduce, as described above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [1, 2, 3].map((n) => n * 10) return?

    map returns a new array of the callback's return values, one per item.
  2. 2. What is [5, 0, 8, null, 3].filter(Boolean)?

    filter keeps items whose callback result is truthy. 0 and null are falsy, so both are removed.
  3. 3. What does [2, 4, 6].reduce((acc, n) => acc + n, 10) return?

    The accumulator starts at 10, then becomes 12, 16 and finally 22.
  4. 4. You need to stop looping as soon as a condition is met. Which is the WRONG tool?

    forEach always visits every item, and break is a syntax error inside its callback.
  5. 5. Why does [].reduce((a, b) => a + b) throw?

    Without an initial value, reduce uses the first item. An empty array has none, so it throws a TypeError. Pass an initial value.

Summary

  • forEach runs a callback for each item, returns undefined and can't stop early; use it for side effects.
  • map returns a new array with one transformed value per item.
  • filter returns a new array with the items whose callback returns a truthy value.
  • reduce folds an array into one value of any type; always pass an initial value.
  • Callbacks receive (item, index, array); arrow functions with braces need an explicit return.
  • Chain filter, map and reduce into readable pipelines, one step per line.

Next: Searching Arrays โ€” find, findIndex, includes, some and every.