Difference between map, filter, and reduce
Learn how map, filter, and reduce work in JavaScript and when to use each for transforming arrays.
Advertisement
Question
What is the difference between map, filter, and reduce?
Answer
All three are higher-order functions for array transformation:
map()transforms each element and returns a new array.filter()returns a new array containing only elements that pass a test.reduce()combines all array values into a single result.
const nums = [1, 2, 3, 4];
const doubled = nums.map((n) => n * 2); // [2,4,6,8]
const evens = nums.filter((n) => n % 2 === 0); // [2,4]
const sum = nums.reduce((acc, n) => acc + n, 0); // 10
Real-World Example
Use map for rendering UI lists in React, filter for search results, and reduce for aggregations like total cart price.
Quick Practice
Write a single chain using map + filter + reduce to square all even numbers in [1,2,3,4,5,6] and return their sum.
Summary
Use map to transform, filter to select, and reduce to summarize — the holy trinity of clean array handling.
Which one modifies the original array?
None of them. They all return new arrays or values and do not mutate the original array.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement