Do you know filter, map, reduce in JavaScript ?

Do you know filter, map & reduce function in JavaScript? If not then you are at the right place and surely you will enjoy this post.

 

I  am pretty much sure in your JavaScript programming life you might face the situation where you have to deal with large array objects where you have to fetch each individual array object and process it. You might need to select specific objects or manipulate the entire objects or find one of the objects.

In above situations, you might have traversed entire array object one by one and then processed it.
Filter, map & reduce these three functions help us to deal such situation. After using these functions our code is much cleaner and easy to understand.

Let’s understand it by an example.

Suppose we have an array of employee objects as shown below. On which we have to perform some operation.

Indiandotnet_Employee_Collection

Now, let’s understand the map, filter & reduce function and compare with traditional way with different cases.

Case 1. Suppose we have to traverse each employee in the array and add the Bonus to their salary. so if we are going to achieve this via traditional way then below snap will show you traditional way.

Indiandotnet_Traditional_Traverse_way

Now, here we can use the map function to make this code more readable format. see, the map function uses as below.

Indiandotnet_MAP

so in nutshell, a map function is used when we want to change each element of the array into another set of values.

Case 2:- Now, suppose if we want only those employee collection whose salary more than 5000 then to achieve this we will use following traditional way.

Traditional_Processing_Way

Now, here we can use the filter function to make this code more readable. See the filter function as below.

Indiandotnet_Filter

So in nutshell filter function is used when we want to filter unwanted objects from an array collection then in such cases, we can use filter function.

Case 3:- Now, suppose if want to sum all the salary amount of employee than in such situation you will write following code

Traditional_Processing_Way

Now here we can use reduce function to make this code more readable. Same above code can be written using reduce.

Indiandotnet_Reduce

So in nutshell reduce function is use when we want cumulative value of array.

I hope you may like these awesome functions.  Please, share your feedback.

Thanks Smile

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.