JavaScript map(), filter() and reduce() With Examples
Most array work boils down to three questions: how do I convert every item, how do I keep only some items, and how do I combine items into one result? JavaScript answers them with map, filter and reduce. Each takes a callback function, calls it for every item, and returns a new value without changing the original array.
map: convert every item
books.map((b) => b.title) calls the arrow once per book and collects the return values into a new array of the same length. Use it whenever the output should have one entry per input.
filter: keep the matches
books.filter((b) => b.genre === "Fiction") keeps the books for which the callback returns a truthy value. The result can be shorter, and it contains the original objects, not copies.
reduce: combine into one value
reduce((sum, b) => sum + b.price, 0) starts with the initial value 0, then calls the callback with the running result (the accumulator) and the next item, and carries the return value forward. After the last item, the accumulator is the answer. reduce can build anything: a number, a string, or an object, such as the count per genre at the end of the example. Always pass the initial value; without it, reduce uses the first item and throws on an empty array.
Expected output
["Paper Cranes", "Kitchen Chemistry", "The Last Lantern"]
2 Paper Cranes, The Last Lantern
43.45
Kitchen Chemistry
true false
2
{Fiction: 2, Nonfiction: 1}Finding and testing
find(fn)returns the first matching item, orundefined.findIndex(fn)returns its position, or-1.some(fn)is true if at least one item matches;every(fn)is true if all of them do. Both stop as soon as the answer is known.
Chaining
Because map and filter return arrays, you can chain them: fiction.map((b) => b.title).join(", "). Read a chain from left to right as a pipeline. If a chain gets long, give the intermediate arrays names.
forEach(fn) runs a callback for each item but returns undefined. Use it only for side effects such as logging; when you want a result, use one of the methods above.
Common mistakes
- Forgetting to
returninside a braced callback:map((b) => { b.title })producesundefineds. - Using
mapjust to loop, throwing away the new array. - Leaving out the initial value of
reduce.
Summary
mapconverts each item,filterkeeps matches,reducefolds everything into one value.find,findIndex,someandeverysearch and test.- None of these change the original array.
Quiz: map, filter, reduce