Simplify Your JavaScript Using Map, Reduce And Filter

Introduction

 
In this article, you will learn how to simplify your Javascript using Map, Reduce, and Filter.

Map Function

If we have an array containing multiple objects and need the name of the object of the person in the array, then, we can map function.
 
Map functions run a callback function for each value in an array and returns each new value in the array
  1. var studentData = [  
  2.   { id: 1, name: 'Amit' },  
  3.   { id: 2, name: 'Swetha' },  
  4.   { id: 3, name: 'Ram' },  
  5.   { id: 4, name: 'Shiv' }  
  6. ];  
  7.   
  8. // using forEach  
  9. var studentNames = [];  
  10. studentData.forEach(function (student) {  
  11.   studentNames.push(student.name);  
  12. });  
  13.   
  14. console.log(studentNames);  
  15.   
  16. const studentNames = studentData.map(student => { return student.name });  
  17.   
  18. // more simpler  
  19. const studentNames = studentData.map(student => student.name);  
  20.   
  21. console.log(studentNames);  
  22. // [ 'Amit', 'Swetha', 'Ram', 'Shiv' ]  

Reduce

 
The Reduce function also runs a callback function for each element of an array, which is same as Map function. However, the difference here is that reduce passes the result of callback from one array element to another element.
  1. var studentData = [  
  2.   { id: 1, name: 'Amit', marks: 50 },  
  3.   { id: 2, name: 'Swetha', marks: 80 },  
  4.   { id: 3, name: 'Ram', marks: 60 },  
  5.   { id: 4, name: 'Shiv', marks: 70 }  
  6. ];  
  7.   
  8. var totalMarks = studentData.reduce((total, student) => {  
  9.   return total + student.marks  
  10. }, 0);  
  11.   
  12. // more simpler  
  13. var totalMarks = studentData.reduce((total, student) => total + student.marks, 0);  
  14.   
  15. console.log(totalMarks);  

Filter

 
In the case that you want to filter some elements from an array, then we can use the filter function.
  1. var studentData = [  
  2.   { id: 1, name: 'Amit', marks: 50 },  
  3.   { id: 2, name: 'Swetha', marks: 80 },  
  4.   { id: 3, name: 'Ram', marks: 60 },  
  5.   { id: 4, name: 'Shiv', marks: 70 }  
  6. ];  
  7.   
  8. var marks = studentData.filter((student) => {  
  9.   return student.marks == 80  
  10. });  
  11.   
  12. // more simpler  
  13. var marks = studentData.filter(student => student.marks == 80);  
  14.   
  15. console.log(marks);  

Summary

 
In this article, we saw how to implement the .map(), .reduce() and .filter() functions in our JavaScript using the ES6 feature.