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.
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.
Now, here we can use the map function to make this code more readable format. See, the map function is used as below:
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:
Now, here we can use the filter
function to make this code more readable. See the filter
function as below:
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:
Now here, we can use reduce
function to make this code more readable. The same code above can be written using 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!