Map() method:
This method is used when you need to do some type of transform on every element. The map method will applying a function to all of its elements in the array and creates a new array. Example,
var persons = [
{ id: 1, name: ‘Kamal’, salary: 2000 },
{ id: 2, name: ‘Korim’, salary: 5000 },
{ id: 3, name: ‘Razzak’, salary: 7000 },
{ id: 4, name: ‘Abdul’, salary: 9000 }
];
We need persons id.
var personsId= persons.map(x=> x.id);
console.log(personsId);
Output: [1, 2, 3, 4]
This new array will always be the same size as the original array, even if you don’t return anything.
Filter() Method:
The filter method creates a new array with all array items that pass the test implemented by the function. The filter method will return an array that is the same size or smaller as the original array.
Use filter method: Filter receives the same arguments as map, and works very similarly.
Example:
var persons = [
{ id: 1, name: ‘Kamal’, salary: 2000 },
{ id: 2, name: ‘Korim’, salary: 5000 },
{ id: 3, name: ‘Razzak’, salary: 7000 },
{ id: 4, name: ‘Abdul’, salary: 9000 }
];
Let’s find out the names of those whose salaries are under 4000.
var newPersons= persons.filter(x=> x.salary>= 4000);
newPersons.forEach(function(person){
console.log(person.name);
});
Output: Korim
Razzak
Abdul
Reduce() Method:
The reduce() method takes an array and apply a function to each item, resulting in a single output value. As a result, an array of numbers we can easily find the total or average of all values.
Example,
var numbers= [0,1,2,3];
var total= numbers.reduce((sum, value)=>sum+value,0);
console.log(total);
Output: 6
Syntax of reduce() method: array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Combining map(), .filter() and reduce():
map() method and filter() method both return arrays. The reduce method return a single value from array. So, we can easily use. example,
var persons = [
{ id: 1, name: ‘Kamal’, salary: 2000 },
{ id: 2, name: ‘Korim’, salary: 5000 },
{ id: 3, name: ‘Razzak’, salary: 7000 },
{ id: 4, name: ‘Abdul’, salary: 9000 }
];
find out the sum of their under salary 4000.
var total= persons.map(x=> x.salary)
.filter(x=> x>= 4000)
.reduce((sum, value)=>sum+value,0);
console.log(total);
Output: 21000