Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Do You Know filter, map, reduce in JavaScript?

4.15/5 (4 votes)
23 Apr 2018CPOL2 min read 7.8K  
Filter, map & reduce function 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 sure that 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 the above situations, you might have traversed entire array object one by one and then processed it.
Filter, map & reduce are three functions help us to deal with such a 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 the 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 the below image will show you the 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 is used as below:

Indiandotnet_MAP

So in a 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 collections whose salary is more than 5000, then to achieve this, we will use the 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 a nutshell, filter function is used when we want to filter unwanted objects from an array collection.

Case 3

Now, suppose you want to sum all the salary amount of employee then in such a situation, you will write the following code:

Traditional_Processing_Way

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

Indiandotnet_Reduce

So in a nutshell, reduce function is used when we want a cumulative value of array.

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

Thanks! Smile

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)