map(), filter(), reduce() in JavaScript Explained with Examples
JavaScript provides powerful array methods that help developers write clean, readable, and efficient code. Among them, map(), filter(), and reduce() are the most commonly used methods in modern JavaScript development.
These methods are widely used in frameworks like Angular, React, and Vue to manipulate and transform data.
In this article, we’ll explore map(), filter(), and reduce() with simple examples.
1. map() – Transform Array Elements
The map() method creates a new array by applying a function to each element of the original array.
It does not modify the original array.
Example
const numbers = [1,2,3,4,5]
const result = numbers.map(n => n * 2);
console.log(result);
Output:
[2, 4, 6, 8, 10]
Real-World Example
const users = [
{
name: 'Bala'
},
{
name: 'Rohit'
},
{
name:'Vicky'
}
]
const result = users.map(n => n.name);
console.log(result);
Output: ['Bala', 'Rohit', 'Vicky']
map() is commonly used when transforming data from APIs.
2. filter() – Select Specific Elements
The filter() method creates a new array with elements that satisfy a condition.
Example
const numbers = [1,2,3,4,5,6]
const result = numbers.filter(n => n%2 === 0);
console.log(result);
Output: [2, 4, 6]
Real-World Example
const users = [
{
name: 'Bala',
age: 20
},
{
name: 'Rohit',
age:25
},
{
name:'Vicky',
age:30
},
{
name:'John',
age:35
},
{
name:'Michael',
age:32
}
]
const result = users.filter((n => n.age > 30));
console.log(result);
Output:
0: {name: 'John', age: 35}
1: {name: 'Michael', age: 32}
filter() is useful for search results, product filtering, and user lists.
3. reduce() – Convert Array into a Single Value
The reduce() method processes each element and reduces the array to a single value.
Example
const numbers = [1,2,3,4,5]
const result = numbers.reduce((acc, num) => acc+num,0)
console.log(result);
Output:15
Real-World Example
const result = cart.reduce((total, item)=> total + item.price,0);
console.log(result);
Output: 70000
reduce() is often used for totals, analytics, and aggregations.
Conclusion
The map(), filter(), and reduce() methods are essential tools for working with arrays in JavaScript. They help developers write clean, concise, and functional code.
Check out more web development articles by clicking the link below.
Top comments (0)