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

var studentData = [  
  { id: 1, name: 'Amit' },  
  { id: 2, name: 'Swetha' },  
  { id: 3, name: 'Ram' },  
  { id: 4, name: 'Shiv' }  
];  
 
// using forEach 
var studentNames = [];  
studentData.forEach(function (student) {  
  studentNames.push(student.name);  
});  
 
console.log(studentNames);  
 
const studentNames = studentData.map(student => { return student.name });  
 
// more simpler 
const studentNames = studentData.map(student => student.name);  
 
console.log(studentNames);  
// [ '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.

var studentData = [  
  { id: 1, name: 'Amit', marks: 50 },  
  { id: 2, name: 'Swetha', marks: 80 },  
  { id: 3, name: 'Ram', marks: 60 },  
  { id: 4, name: 'Shiv', marks: 70 }  
];  
 
var totalMarks = studentData.reduce((total, student) => {  
 return total + student.marks  
}, 0);  
 
// more simpler 
var totalMarks = studentData.reduce((total, student) => total + student.marks, 0);  
 
console.log(totalMarks);  

Filter


In the case that you want to filter some elements from an array, then we can use the filter function.

var studentData = [  
  { id: 1, name: 'Amit', marks: 50 },  
  { id: 2, name: 'Swetha', marks: 80 },  
  { id: 3, name: 'Ram', marks: 60 },  
  { id: 4, name: 'Shiv', marks: 70 }  
];  
 
var marks = studentData.filter((student) => {  
 return student.marks == 80  
});  
 
// more simpler 
var marks = studentData.filter(student => student.marks == 80);  
 
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.


Source:Paper.com

Recent Posts

See All