function groupByKey(array, key) {
return array
.reduce((hash, obj) => {
if(obj[key] === undefined) return hash;
return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
}, {})
}
var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];
var result = groupByKey(cars, 'make');
JSON.stringify(result,""," ");
{
"audi": [
{
"make": "audi",
"model": "r8",
"year": "2012"
},
{
"make": "audi",
"model": "rs5",
"year": "2013"
}
],
"ford": [
{
"make": "ford",
"model": "mustang",
"year": "2012"
},
{
"make": "ford",
"model": "fusion",
"year": "2015"
}
],
"kia": [
{
"make": "kia",
"model": "optima",
"year": "2012"
}
]
}
var results = orgs.reduce(function(results, org) {
(results[org.id] = results[org.id] || []).push(org);
return results;
}, {})
const groupBy = (arr, prop) =>
arr.reduce((acc, val) => {
;(acc[val[prop]] = acc[val[prop]] || []).push(val)
return acc
}, {})
let group = cars.reduce((r, a) => { console.log("a", a); console.log('r', r); r[a.make] = [...r[a.make] || [], a]; return r;}, {});console.log("group", group);