Map, Filter and Reduce Operators in JavaScript
Today we will provide you an understanding of the Map, Filter and Reduce Operators in JavaScript. These three operators are very useful in JS development.
Map, Filter and Reduce Operators in JavaScript, Understanding map, filter and reduce in React JS, map, filter, reduce javascript examples, What is map, filter and reduce.
Checkout more articles on JavaScript
- Default Parameters in JavaScript
- Rest Parameters in JavaScript
- Replace all occurrences of a string in JavaScript
- How to Sort an Array in JavaScript
- Do’s and don’ts in JavaScript
In Order to understand, let's start with an example. Consider the below variable with default value.
const products = [
{
"name": "product 1",
"size": "small",
"weight": 50
},
{
"name": "product 2",
"size": "small",
"weight": 100
},
{
"name": "product 3",
"size": "medium",
"weight": 150
},
{
"name": "product 4",
"size": "big",
"weight": 500
}
]
Understanding of the Map, Filter and Reduce Operators
1. Map Operator
If I already have an array and I want to do the exact same operation on each of the elements in the array and return the same amount of items in the array, use the map.
let product_list = products.map((product, index, products) => {
return product.name
});
// Output: ["product 1", "product 2", "product 3", "product 4"]
In the above example we will have an array of product names.
2. Filter Operator
If I already have an array but I only want to have items in the array that match certain criteria, use the filter.
let small_products = products.filter((product, index, products) => {
return product.size === "small"
});
// Output: [{"name":"product 1","size":"small","weight":50},{"name":"product 2","size":"small","weight":100}]
3 Reduce Operator
If I already have an array, but I want to use the values in that array to create something completely new, use the reduce.
let total_weight = products.reduce((weight, product, index, products) => {
return weight += product.weight
}, 10);
// Output: 810
Let's take the understanding of the parameters. Reduce function has two major parameters.
-
The first parameter is the callback function and the second parameter is initial value.
-
The callback function has four parameters.
- The first parameter is the initial value or the previously returned value of the function. In our case it's `10`. You can set any value as per your requirement.
- The second parameter is the current element in the array.
- The third parameter is the index of the current element.
- The last is the full array.
NOTE: If you are not define the initial value then by default it will consider the first element of an array as a initial value.
That's it for today.
Thank you for reading. Happy Coding!