Simplify Map(), Reduce() And Filter() In TypeScript

If you are a front-end developer, day to day you may come across many functions which can confuse you and make it difficult for you to use them appropriately.
 
In this article, I am going to explain some functions like .map(), .reduce(), filter(), find(), etc. which play an important role when one wants to transform the array of play with JSON responses.
 
Let’s start with them one by one,
 

map()

 
It is an array function that transforms the array according to the applied function and returns the updated array. It works on each element of an array.
 
Syntax
 
array.map(callback[,object])
 
callback - It is a function that provides an element of the new Array from an element of the current one.
object - object to use as this when executing callback.
 
Return Type - List
 
Examples
 
Calculate cube of each element with the help of map. 
  1. function cube(n){  
  2.    return n*n*n;  
  3. }  
  4. var arr=new Array(1,2,3,4)  
  5. var newArr=arr.map(cube);  
  6. console.log(newArr)  // Output : [1,8,27,64]
In the above example, a function called “cube” is created and then is passed as a callback function into map().
 
Consider the below example, where er manipulates the array element and transfers it into key and value pairs.
  1. var arr = [2,5,6,8,9];  
  2. var newArr = arr.map(function(val,index){  
  3.    console.log(“Key”:index, “Value”:val*val)  
  4. });  
Now, sometimes there could be a list of object like :
  1. var employees = [  
  2.    { id: 20, name: 'Ajay', salary:30000 },  
  3.    { id: 24, name: 'Vijay', salary:35000 },  
  4.    { id: 56, name: 'Rahul', salary:32000 },  
  5.    { id: 88, name: 'Raman', salary:38000 }  
  6. ];  

And from the above list, if you wish to create a new list having one property only, like you want the list of salary, then you have to use map() function like :

  1. var empSalary= employees.map(function(employee) {  
  2.    return employee.salary;  
  3. }  
  4. console.log(empSalary)  //output => [30000,35000,32000,38000]  

filter()

 
As the name suggests it can filter out the data/array elements on the basis of condition and return the result as a list. Basically, this function pushes the current element into a new array when the callback functions return true.
 
Syntax
 
array.map(callback[,object])
 
callback - it is a function that provides an element of the new Array from an element of the current one.
object - object to use as this when executing callback.
 
Return Type : List
 
Examples
  1. //Calculate a list of even elements from an array :    
  2. arr = new Array(1, 2, 3, 6, 5, 4)  
  3. var newArr = arr.filter(function(record) {  
  4.     return record % 2 == 0;  
  5. }); // output => [2,6,4]     
Calculate factorial with the help of filter,
  1. function factorial(value) {  
  2.     let ans = 1;  
  3.     for (let i = 2; i <= value; i++) ans = ans * i  
  4.     return ans;  
  5. }  
  6. var arr = new Array(3, 4, 5, 6)  
  7. var newArray = arr.filter(factorial)  
  8. console.log(newArray) //output=> [6,24,120,720]      
Now, sometimes you have a list of object like,
  1. var employees = [{  
  2.     id: 20,  
  3.     name: 'Ajay',  
  4.     salary: 30000. dept: ’it’  
  5. }, {  
  6.     id: 24,  
  7.     name: 'Vijay',  
  8.     salary: 35000,  
  9.     dept: ’hr’  
  10. }, {  
  11.     id: 56,  
  12.     name: 'Rahul',  
  13.     salary: 32000,  
  14.     dept: ’it’  
  15. }, {  
  16.     id: 88,  
  17.     name: 'Raman',  
  18.     salary: 38000,  
  19.     dept: ’hr’  
  20. }];   
And from the above list, if you want to create a new list of IT departments, then you will use filter() function like: 
  1. var departmentList = employees.filter(function(record){  
  2.    return record.dept == “it”;  
  3. });  
  4. console.log(departmentList);  
  5. //output [{ id: 20, name: 'Ajay', salary:30000. dept:’it’ },      // { id: 56, name: 'Rahul', salary:32000, dept:’it’ }]  

find()

 
This method returns the value of the first element in the provided array that satisfies the provided testing function. It is very similar to a filter function except that it will find only the first match value. If an element does not satisfy the condition, then it will return #ff0000.
 
Syntax
 
array.find(callback[,object])
 
callback - function to test for each element.
object - object to use as this when executing callback.
 
Example
  1. const array1 = [5, 12, 8, 130, 44];  
  2. const found = array1.find(element => element > 10);  
  3. console.log(found);    
  4. //output => 12  
As in the above example, there are 3 elements that are greater than 10, but it will display only the first matching element i.e. 12. However, if you will use filter() here then you will get a list of 3 elements, i.e. 12, 130, and 44.
 
Consider another example with list of objects like,
  1. var employees = [  
  2.    { id: 20, name: 'Ajay', salary:30000 },  
  3.    { id: 24, name: 'Vijay', salary:35000 },  
  4.    { id: 56, name: 'Rahul', salary:32000 },  
  5.    { id: 88, name: 'Raman', salary:38000 }  
  6. ];  
  7.   
  8. var employee= employees.find(function (record) {  
  9.    return record.id == 56;  
  10. });  
  11.   
  12. //output :- { id: 56, name: 'Rahul', salary:32000 }  
Some methods are very similar to find() like findIndex(), indexOf() and includes(). Let's discuss these methods
 

findIndex()

 
This method returns the index of the first element in the array that satisfies the provided testing function.
 
Example
  1. const array1 = [5, 12, 8, 130, 44];  
  2. const found = array1.findIndex(element => element > 10);  
  3. console.log(found);  
  4.   
  5. //In above example you will get the position of 12 i.e. 1.  

indexOf()

 
This function is very similar to findIndex(), even this function also returns the index of the first element.
 
Now, the question that arises is, what is the difference between findIndex() and indexOf()?
 
The major difference is the parameters of both the functions, i.e.
  • indexOf() - expects only a value as the first parameter (not take any callback function). So, it is a better choice to find the index in arrays of primitive types like number, string, and boolean.
  • findIndex() - expects a callback as the first parameter. By the help of this callback function, you will give a condition to find an element. So, it is a better choice to use this when you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.

includes()

 
It is similar to indexOf(), i.e. both can be used to find elements in an array, however, indexOf() returns a number (-1 if element not present in the array, or array position if the element is present). But, includes() returns a boolean value (true or false)

reduce()

 
It also works on a callback for each element of an array. It reduces the result of this callback function from one array element to the other.
 
Syntax
 
array.reduce(callback[,initalValue])
 
callback - this parameter is the function to execute on each value in the array.
intitalValue - this parameter is the object to use as the first argument of the first call of the callback.
 
Examples
 
To calculate product of every element of an array,
  1. var arr = new Array (1,2,3,4,5)    
  2. var val = arr.reduce(function(a,b){    
  3.    return a*b;    
  4. });      
  5. //output => 120    
Calculate the total salary from a list of object, then you will use the reduce() like,
  1. var employees = [    
  2.    { id: 20, name: 'Ajay', salary:30000 },    
  3.    { id: 24, name: 'Vijay', salary:35000 },    
  4.    { id: 56, name: 'Rahul', salary:32000 },    
  5.    { id: 88, name: 'Raman', salary:38000 }    
  6. ];    
  7. var totalSalary= employees .reduce(function (total, record) {    
  8.    return total + record.salary;    
  9. }, 0);    
  10.     
  11. //It will return the total salary of all the employees.     
This all about the basic use of the above function. Now, let’s consider one more example where there is a complex list of objects and one has to find data on the basis of condition.
  1. var employees= [  
  2.       { id: 10, name: "Ajay", years: 14, salary:40000, dept:'it' },  
  3.       { id: 2, name: "Vijay", years: 30, salary:35000, dept:'hr' },  
  4.       { id: 41, name: "Rahul",years: 16, salary:45000, dept:'hr'},  
  5.       { id: 99, name: "Raman",years: 22, salary:35000,dept:'it'}  
  6. ];  
Now, from the above data, suppose you have to calculate total salary on the basis of department, then the below code would be used where filter(), reduce() and map() function can be mixed.
  1. var deptList = [...new Set(pilotList.map(function(item) {  
  2.     return item.dept;  
  3. }, 0))];  
  4. //with the help of above code first all the unique department list is found i.e it will return [‘it’,’hr’], now on the basis of that list the total will be found.    
  5. var deptList1 = deptList.map(function(item) {  
  6.     var totalSal = employees.filter(function(record) {  
  7.         return record.dept === item  
  8.     }).reduce(function(tot, employee) {  
  9.         return tot + employee.salary;  
  10.     }, 0)  
  11.     return {  
  12.         'dept': item,  
  13.         'total': totalSal  
  14.     }  
  15. }, 0);  
  16. //output : {'dept':'it', 'total':75000} {'dept':'hr', 'total':80000}     

Summary

 
It may be a little tricky to remember all the functions and their use. So, for this here is a picture that anyone can easily memorize.
 
map(), filter(), reduce()

Conclusion

 
Through this article, the use of .map(), filter(), reduce() and other functions can be understood in a better way.
 
I hope after reading this article, you can easily use these functions. All the queries related to this article are always welcomed. Thanks for reading.!!!