Map, Filter and Reduce
The Holy Trinity of Array Methods
In modern frontend frameworks (especially React), you will rarely use traditional loops. Instead, you will use map(), filter(), and reduce(). These are "higher-order methods" that do not modify the original array; instead, they return a brand new array.
1. Array.map()
map() iterates over an array and returns a new array with the results of a function applied to every element.
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
In React, you use map() to convert an array of data into an array of UI components.
2. Array.filter()
filter() iterates over an array and returns a new array containing ONLY the items that pass a specific test (condition).
let ages = [12, 18, 25, 15];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 25]
3. Array.reduce()
reduce() is the most powerful (and most complex). It iterates over an array and "reduces" it down to a single value (like calculating a sum).
let prices = [10, 20, 30];
let total = prices.reduce((accumulator, currentPrice) => {
return accumulator + currentPrice;
}, 0); // 0 is the starting value
console.log(total); // 60
💡 Himanshu's Tip:
If there is one thing you master in this entire Fundamentals course, make it map() and filter(). You will use them literally every single day as a React developer.
Interview Questions
- Do
map()andfilter()modify the original array? - What is the difference between
forEach()andmap()? - In the
reduce()method, what does the accumulator parameter do?