Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of map, reduce, and filter composed to create hero stats.
/* Map, Reduce, Filter - Composing The functions
* Create Warrior classes using the stats below
* Filter Stats above 50 and reduce it to a single value
* called heroStat with the composition of all their stats
*/
const stats = [10, 20, 30, 50, 70, 80];
/* ES5 Example */
//Map stat numbers into class warrior object
const warriors = stats.map(function (element) { return Object.assign({ class: 'Warrior', stat: element }); });
//filter warriors with stats above 50
const heroStats = warriors.filter(function (element) { return element.stat > 50; })
.reduce(function (start, curr) {
//return warrior stats from the beginning of the way
return start.stat + curr.stat;
});
const hero = { class: 'Hero', stat: heroStats };
console.log('Hero Stats', hero); // Hero Stats { class: 'Hero', stat: 150 }
/* ES6 Example */
const warriors2 = stats.map((element) => { return Object.assign({ class: 'Warrior', stat: element }); });
console.log(warriors); // [{class: 'Warrior', stat: 10}, {class: 'Warrior', stat: 20}...]
const heroStats2 = warriors2.filter((element) => element.stat > 50)
.reduce((start, curr) => {
return start.stat + curr.stat;
});
const hero2 = { class: 'Hero', stat: heroStats2 };
console.log(hero2); // { class: 'Hero', stat: 150 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment