How to use map() reduce() and filter() ?
In javascript to perform operations in the array of objects we can use .map(),.reduce(),.filter().
.map()
The map function is capable of accessing each object in an array and perform the desired operation on the each item of an array.
Let's look at the above example, a new array groceryNames is created by the map function which stores only the the names of the groceries stored in array of objects.The map function performs the callback for each value in the array and returns each new value in the resulting array.
It becomes even more easier when we use arrow function in map
.reduce
As the name shows the .reduce() function reduces the values inside an array.The reduce passes the result of this callback (the accumulator) from one array element to the other.
The accumulator can be pretty much anything (integer, string, object, etc.) and must be instantiated or passed when calling .reduce()
After running the callback for each element of the array, reduce will return the final value of our accumulator (i.e 120).The 0 is the initial value of an accumulator,if we change value ,say 10, the resultant value would be 130.
.filter
Obviously the filter operation filters the values of an array based on certain condition and stores them in a new array.
Now let us consider a scenario where we need to get the rate of Non-veg items.We can combine these methods to get the rate from the grocery array.
Top comments (0)