codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript — Learn to Chain Map, Filter, and Reduce

Brandon Morelli
codeburst
Published in
4 min readNov 19, 2017

--

This is article #4 in a four part series this week.

Chaining Map, Filter, & Reduce

data = [
{
name: 'Butters',
age: 3,
type: 'dog'
},
{
name: 'Lizzy',
age: 6,
type: 'dog'
},
{
name: 'Red',
age: 1,
type: 'cat'
},
{
name: 'Joey',
age: 3,
type: 'dog'
},
];
function getAges(data) {
let sum = 0;
for (var i = 0; i < data.length; i++){
if (data[i].type === 'dog'){
let tempAge = data[i].age;
sum += (tempAge * 7);
}
}
return sum;
}
// getAges(data) = 84
let ages = data.filter((animal) => {
return animal.type === 'dog';
})
.map((animal) => {
return animal.age *= 7
})
.reduce((sum, animal) => {
return sum + animal.age;
});
let ages = data
.filter((animal) => {
return animal.type === 'dog';
}).map((animal) => {
return animal.age * 7
}).reduce((sum, animal) => {
return sum + animal.age;
});
// ages = 84
let isDog = (animal) => {
return animal.type === 'dog';
}
let dogYears = (animal) => {
return animal.age * 7;
}
let sum = (sum, animal) => {
return sum + animal;
}
let ages = data
.filter(isDog)
.map(dogYears)
.reduce(sum);
// ages = 84

Closing Notes:

If this post was helpful, please click the clap 👏button below a few times to show your support! ⬇⬇

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (30)