MAP(), FILTER(), REDUCE()
Array methods like map(), filter(), and reduce() are very important in modern JavaScript. They help you work with arrays in a clean and readable way.
Let’s understand them with simple examples.
1️⃣ map() – Transform Every Item
map() is used when you want to change every element in an array and return a new array.
Example: Square of numbers
const numbers = [1, 2, 3, 4];
const squares = numbers.map(num => num * num);
console.log(squares);
Output:
[1, 4, 9, 16]
How it works
Goes through each element
Applies a function
Returns a new array
Visualization
[1,2,3,4]
↓ map
[num*num]
[1,4,9,16]
2️⃣ filter() – Select Specific Items
filter() is used to keep only the elements that match a condition.
Example: Get even numbers
const numbers = [1,2,3,4,5,6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
Output:
[2,4,6]
How it works
[1,2,3,4,5,6]
↓ filter
[num % 2 === 0]
[2,4,6]
3️⃣ reduce() – Combine Values into One
reduce() is used to reduce an array into a single value.
Example: Sum of numbers
const numbers = [1,2,3,4];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum);
Output
10
How it works
Start: 0
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
4️⃣ Quick Comparison
| Method | Purpose | Result |
|---|---|---|
| map() | Transform items | New array |
| filter() | Select items | New array |
| reduce() | Combine items | Single value |
5️⃣ Realistic Example
const users = [
{name:"Aman", age:18},
{name:"Riya", age:25},
{name:"Raj", age:30}
];
const adults = users
.filter(user => user.age >= 21)
.map(user => user.name);
console.log(adults);
Output
["Riya","Raj"]
✅ Memory Trick
map → modify
filter → select
reduce → combine