DEV Community

Sarulatha
Sarulatha

Posted on

How to use map() reduce() and filter() ?

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.

Alt Text

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

Alt Text

.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()

Alt Text

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.

In ES6,using arrow function
Alt Text

.filter

Obviously the filter operation filters the values of an array based on certain condition and stores them in a new array.

Alt Text

Using arrow function,
Alt Text

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.

Alt Text

Top comments (0)