What is the difference between map, filter and reduce?
Quick Answer
map transforms each element and returns a new array of the same length. filter keeps elements that pass a test and returns a shorter (or equal) array. reduce folds the array into a single value (sum, object, grouped map) using an accumulator. All three return new values and don't mutate the source.
map takes each element and returns a transformed one, so you get a new array the same length. filter runs a predicate and returns only the elements that pass. reduce collapses the whole array into one value using an accumulator — a sum, or an object, or a grouped structure. None of them mutate the original array, which is why they're preferred in things like React. I use reduce when I'm aggregating, but if a map then filter reads more clearly I'll take the small performance hit of two passes.
[1,2,3].map(x => x * 2)→[2,4,6].[1,2,3,4].filter(x => x % 2 === 0)→[2,4].[1,2,3,4].reduce((sum, x) => sum + x, 0)→10.reducecan build anything — group by a key, count occurrences, flatten — but if a simplemap/filter/for...ofis clearer, use that.- Chaining
filter().map()iterates twice; for huge arrays a singlereduceor loop is faster, but readability usually wins.