Coding · 4 MIN READ
JavaScript map, filter, and reduce: choose by the result
Choose the right array method with concrete JavaScript examples, a reference pitfall, and a three-question quiz.
By SpawnLearn · Updated
Map transforms each element
Use map when you want a new array of callback results. For a dense array, [3, 6, 9].map(n => n * 2) produces [6, 12, 18]. Think of changing each value rather than selecting which values survive.
Filter keeps matching elements
Use filter when you want to keep elements that pass a test. [3, 6, 9].filter(n => n > 4) produces [6, 9]. The callback supplies the decision; the resulting array contains the matching original elements, not the callback's true or false values.
Reduce carries a result forward
Use reduce when each step updates an accumulator. [3, 6, 9].reduce((sum, n) => sum + n, 0) produces 18. The final argument supplies the starting value. An explicit starting value makes the empty-array case predictable: this sum returns 0 for an empty array.
A new array is not a deep copy
Map and filter return new arrays, but objects inside them can still be shared with the original array. A callback that returns the same object does not clone it. Mutating that object's properties through either array changes the shared object. Keep transformation callbacks free of unexpected side effects.
Keep this in mind: Transform with map, select with filter, accumulate with reduce.
Go a little deeper
Three questions. See what sticks.
No account needed. Read the feedback before moving on.
This guest round is not saved. Create an account to save future rounds and revisit the puzzle types you miss.