Example - filter map reduce
Showing how to combine the array methods. In the following example function running filter, map and reduce.const bands = [
{name: "Beastie Boys", category: "Rap", start: 1979, end: 2012},
{name: "Nirvana", category: "Grunge", start: 1987, end: 1994},
{name: "Run DMC", category: "Rap", start: 1981, end: 2002},
{name: "Sound Garden", category: "Grunge", start: 1984, end: 1997},
{name: "Queen", category: "Rock", start: 1970, end: 1991},
{name: "The Beatles", category: "Pop", start: 1960, end: 1970}
];
const getTotalAge = cat => {
return bands.filter(band => band.category === cat)
.map(band => band.end - band.start)
.reduce((total, age) => total + age,0);
}
const totalAge = getTotalAge('Rap');
Filter:Returns an array of band objects based on category.
[{name:"Beastie Boys", category: "Rap", start: 1979, end: 2012}, {name: "Run DMC", category: "Rap", start: 1981, end: 2002}]
Map:
Returns array of just the band ages.
[33,21]
Reduce:
Returns the sum of all the ages.
33 + 21 = 54
RESULT totalAge