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.
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.
Now, here we can use the map function to make this code more readable format. see, the map function uses as below.
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.
Now, here we can use the filter function to make this code more readable. See the filter function as below.
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
Now here we can use reduce function to make this code more readable. Same above code can be written using 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.