Array Methods: map, filter, reduce
The transformations you will reach for in every list you render.
What you'll learn
map,filter, andreduce, and how to tell which one you need- Why these return new arrays instead of changing the original
- Chaining transformations into a readable pipeline
- The mutating methods to be careful with
Why these three
Rendering a list in React means turning an array of data into an array of elements. You do not write a loop and push into an array — you describe the transformation. These three cover nearly all of it:
map— same number of items, each one transformedfilter— fewer items, each one unchangedreduce— many items in, a single value out
Each returns a new array (or value) and leaves the original alone.
map
map calls your function once per item and collects the results.
The callback also receives the index, which is how list rendering in React gets its position when there is no better identifier:
map vs forEach
forEach runs your function for its side effects and returns undefined.
map returns the transformed array. If you want a result, use map:
filter
filter keeps the items for which your function returns a truthy value.
A common use is removing an item without mutating the array — the pattern behind almost every "delete" button in a React app:
reduce
reduce folds an array down to a single value. It takes an accumulator and the
current item, and returns the next accumulator. The second argument is the
starting value.
The result does not have to be a number. Grouping items into an object is one
of the most useful things reduce does:
Always pass the initial value. Without it, reduce uses the first item as the
starting accumulator — and throws on an empty array.
Chaining
Because each method returns a new array, they compose into a pipeline that reads top to bottom:
Filter before you map when you can — there is no point transforming items you are about to discard.
Methods that mutate
Some array methods change the array in place. They are worth knowing precisely so you can avoid them on data you do not own:
push, pop, splice, sort, and reverse all mutate. map, filter,
slice, concat, and spread all copy.
Common mistakes
- Using
forEachwhen you want a result. It always returnsundefined. - Forgetting
reduce's initial value. It changes the behaviour and throws on empty arrays. - Sorting state directly.
sortmutates; copy first. - Forgetting the callback's return.
(n) => { n * 2 }returns nothing — drop the braces or addreturn.
Exercise
Produce the names of active users with more than 10 points, in one chain.
Expected output: ["Ada", "Alan"].