I first came across this code on JamieMason's gist. Here I've tried to re-create it from scratch as I found their solution slightly hard to follow.
function groupBy(key) {
return function group(array) {
return array.reduce((acc, obj) => {
const property = obj[key];
acc[property] = acc[property] || [];
acc[property].push(obj);
return acc;
}, {});
}
}
const dogs = [
{ name: 'Biscuit', age: '23', 'color': 'black '},
{ name: 'Diamond', age: '21', 'color': 'white '},
{ name: 'Oreo', age: '20', 'color': 'yellow '},
{ name: 'Zelda', age: '19', 'color': 'red'},
{ name: 'Snuggles', age: '23', 'color': 'red '},
{ name: 'Ron Burgandy', age: '23', 'color': 'black '},
];
const groupByAge = groupBy('age');
console.log(groupByAge(dogs));
{
'19': [ { name: 'Zelda', age: '19', color: 'red' } ],
'20': [ { name: 'Oreo', age: '20', color: 'yellow ' } ],
'21': [ { name: 'Diamond', age: '21', color: 'white ' } ],
'23': [
{ name: 'Biscuit', age: '23', color: 'black ' },
{ name: 'Snuggles', age: '23', color: 'red ' },
{ name: 'Ron Burgandy', age: '23', color: 'black ' }
]
}
P.S. I'm aware that most dogs don't live to be 23 years old. RIP biscuit.