group elements by key in javascript code example
Example 1: javascript group by property array of objects
function groupArrayOfObjects(list, key) {
return list.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
var groupedPeople=groupArrayOfObjects(people,"sex");
console.log(groupedPeople.Male);
console.log(groupedPeople.Female);
Example 2: javascript group by key
result = array.reduce((h, obj) => Object.assign(h, { [obj.key]:( h[obj.key] || [] ).concat(obj) }), {})