Array Iteration: map, filter, reduce

Ditch the classic for-loop. Learn how to process, filter, and summarize arrays using modern declarative functions.

JavaScript8 min readConcept 27 of 62

Higher-Order Functions

Historically, developers used for loops to process arrays. Modern JavaScript uses 'higher-order functions' - functions that accept *other* functions as arguments - to iterate declaratively.

Instead of telling the computer *how* to loop, you simply tell it *what* to do with each item.

Map and Filter

map() runs your callback function on every item in the array and returns a brand new array of the exact same length containing the transformed results. It is perfect for converting data (e.g., turning an array of strings into an array of React components).

filter() runs your callback function as a test. If the callback returns true, the item is kept. If false, it is discarded. It returns a new array that is usually shorter than the original.

Reduce and Chaining

reduce() is the ultimate Swiss Army knife. It takes an array and 'reduces' it down to a single value, like a sum of numbers or a single combined object. It requires a callback and an initial starting value.

Because map and filter both return new arrays, you can **chain** them together! You can filter out bad data, map the good data, and reduce it to a final answer in one elegant, unbroken line of code.

The Assembly Line

Step through a chained operation to see how data flows from a map, into a filter, and finally into a reduce.

The Assembly Line

const result = [1, 2, 3, 4]
.map(n => n * 10)
.filter(n => n > 20)
.reduce((sum, n) => sum + n, 0);
Pipeline Output
Initial Array
1
2
3
4
iBecause map and filter return brand new arrays instead of mutating, they can be flawlessly chained together into a single pipeline!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Which method would you use if you have an array of 10 users, and you want to create an array of just their 10 email addresses?
  2. 2Why can you chain `.map().filter()` together?
  3. 3What happens if a `filter()` callback returns `false` for every single item in the array?

Remember this

  • map() transforms data 1-to-1, returning a new array of the same length.
  • filter() tests data, returning a new array containing only items that passed.
  • reduce() boils an entire array down into a single value.
  • These methods are safe because they do not mutate the original array.
  • Because map and filter return arrays, they can be chained together sequentially.

Done with this concept?

Mark it complete to track your progress. No login needed.