Redefining JavaScript loops – filter map and reduce

0
438
filter map and reduce

Redefining JavaScript loops – filter map and reduce

In JavaScript we have been writing loops , like we do in any programming language . Today we are going to check JavaScript  filter , map and reduce . These are a part of JavaScript Functional Programming .

We are not going to deep dive into the concepts of functional programming in java script . Lets get started and have  a look at these concepts.

Have a look what MDN Says about these JavaScript filter map and reduce :-

  1. Filter In Javascript  :- As the name suggests, it returns an array with filtered  items from the original array
  2. Map In Javascript :- Used to create a new array by iterating existing array
  3. Reduce  In Javascript  :- Returns a single object .

We are going to take following example where we have an array of employees and we are going to do some operations on this array to demonstrate JavaScript filter map and reduce.




How to use Filter In JavaScript  :-

How Would you Find Out Employees Whose age is less than 50 here in above employee array ?

In a Normal JavaScript we would do something below as shown ,

Now We have a different Way of Doing this using Javascript Filter .

JavaScript Filter we can pass two arguments inside a callback function , actual object and index .

We can also Write same thing using ES6 syntax as below .

Output:-

How to use JavaScript Map  :-

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Output :-

How to Use JavaScript Reduce :- reduce()  works on an array and returns a single object .We are going to write a code works on an array and reduce to compute the total value of age of users  array .

Lets See How We can achieve this :-

In the above example we are passing two parameters to the callback function , total is known as accumulator. The Job of accumulator is it accumulates the callback’s values . It is the accumulated value previously returned . In this case we have initialized our accumulator with zero value .

So once the first element of array is traversed accumulator total will have 0+age of First employee. Now this value is passed to the next callback function for second array item and so on.

Now We Can simplify the above JavaScript reduce() code using ES6 syntax as :

 

Please Comment if You Want some More examples or You are stuck at any place .We will be happy to help you ! Thanks !

 

 

 

 

 

 

 

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here