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
Output: [2, 4, 6, 8, 10]
Real-World Example
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
Output: [2, 4, 6]
Real-World Example
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
Output:15
Real-World Example
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.






No comments:
Post a Comment