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
In Order to understand, let’s start with an example. Consider the below variable with default value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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.
1 2 3 4 | 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.
1 2 3 4 | 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.
1 2 3 4 | 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.
- The first parameter is the initial value or the previously returned value of the function. In our case it’s
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!