Example 1: javascript group by key
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' }],
result = cars.reduce(function (r, a) {
r[a.make] = r[a.make] || [];
r[a.make].push(a);
return r;
}, Object.create(null));
console.log(result);
Example 2: javascript array group by
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,"","\t");
{
"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"
}
]
}
Example 3: group objects in javascript
function groupBy(arr, prop) {
const map = new Map(Array.from(arr, obj => [obj[prop], []]));
arr.forEach(obj => map.get(obj[prop]).push(obj));
return Array.from(map.values());
}
const data = [{ name: "Display", group: "Technical detals", id: 60, value: 4 }, { name: "Manufacturer", group: "Manufacturer", id: 58, value: "Apple" }, { name: "OS", group: "Technical detals", id: 37, value: "Apple iOS" }];
console.log(groupBy(data, "group"));