Skip to content

Instantly share code, notes, and snippets.

@TCotton
Last active August 12, 2017 18:43
Show Gist options
  • Save TCotton/9f9fef1ccc4f49ae3a449f9699efd953 to your computer and use it in GitHub Desktop.
Save TCotton/9f9fef1ccc4f49ae3a449f9699efd953 to your computer and use it in GitHub Desktop.
clear reduce example
let footballPlayers = [{
gender: "M",
name: "Karim Benzema",
age: 29,
club: "Real Madrid CF",
country: "Spain"
},
{
gender: "M",
name: "Samir Nasri",
age: 29,
club: "Sevilla FC",
country: "Spain"
},
{
gender: "M",
name: "Hatem Ben Arfa",
age: 29,
club: "PSG",
country: "France"
},
{
gender: "M",
name: "Radamel Falcao",
age: 27,
club: "AS Monaco FC",
country: "France"
},
{
gender: "M",
name: "Riyad Mahrez",
age: 25,
club: "Leicester City FC",
country: "England"
},
{
gender: "M",
name: "Sofiane Feghouli",
age: 26,
club: "West Ham United",
country: "England"
}
];
let playersByCountry = footballPlayers.reduce((players, player, index) => {
if (player.country === "France") {
players.france.push(player)
} else if (player.country === "England") {
players.england.push(player)
} else if (player.country === "Spain") {
players.spain.push(player)
}
return players
}, {
france: [],
england: [],
spain: []
});
console.dir(JSON.stringify(playersByCountry));
{
"france": [{
"gender": "M",
"name": "Hatem Ben Arfa",
"age": 29,
"club": "PSG",
"country": "France"
}, {
"gender": "M",
"name": "Radamel Falcao",
"age": 27,
"club": "AS Monaco FC",
"country": "France"
}],
"england": [{
"gender": "M",
"name": "Riyad Mahrez",
"age": 25,
"club": "Leicester City FC",
"country": "England"
}, {
"gender": "M",
"name": "Sofiane Feghouli",
"age": 26,
"club": "West Ham United",
"country": "England"
}],
"spain": [{
"gender": "M",
"name": "Karim Benzema",
"age": 29,
"club": "Real Madrid CF",
"country": "Spain"
}, {
"gender": "M",
"name": "Samir Nasri",
"age": 29,
"club": "Sevilla FC",
"country": "Spain"
}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment