← All concepts
Working With Arrays

map, filter, and reduce

map transforms every element, filter keeps a subset, and reduce folds everything into one value.

Loading visual…

Definition

map calls a function on every element of an array and returns a brand new array of the same length, made up of whatever that function returns for each element. The original array is left untouched, and no elements are added or removed, only transformed. filter also calls a function on every element, but it keeps the element only when that function returns a truthy value, dropping the rest. The result is a new array that can be shorter than the original, or the same length if everything passes, but it is never longer. reduce walks the array from left to right, calling a function with an accumulator and the current element, and returns whatever that function produces as the new accumulator for the next step. Given an initial value as its second argument, reduce starts the accumulator there and folds every element into it one at a time, ending with a single value, a sum, an object, another array, whatever the callback builds. Chaining the three together, nums.map(...).filter(...).reduce(...), is a common way to transform, narrow, and total a list in one readable pipeline.

Examples

[1, 2, 3].map((n) => n * 2);
// [2, 4, 6]

map returns a new array of the same length, with each value transformed independently of the others.

[1, -2, 3, -4].filter((n) => n > 0);
// [1, 3]

filter keeps only the elements where the callback returns true, so the result can be shorter than the input.

[1, 2, 3, 4].reduce((total, n) => total + n, 0);
// 10

reduce walks the array left to right, folding each value into the accumulator that started at the initial value, 0.

Where you see this

Practice this

Further reading