1function groupArrayOfObjects(list, key) {
2 return list.reduce(function(rv, x) {
3 (rv[x[key]] = rv[x[key]] || []).push(x);
4 return rv;
5 }, {});
6};
7
8var people = [
9 {sex:"Male", name:"Jeff"},
10 {sex:"Female", name:"Megan"},
11 {sex:"Male", name:"Taylor"},
12 {sex:"Female", name:"Madison"}
13];
14var groupedPeople=groupArrayOfObjects(people,"sex");
15console.log(groupedPeople.Male);//will be the Males
16console.log(groupedPeople.Female);//will be the Females
1var 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' }],
2 result = cars.reduce(function (r, a) {
3 r[a.make] = r[a.make] || [];
4 r[a.make].push(a);
5 return r;
6 }, Object.create(null));
7
8console.log(result);
1result = array.reduce((h, obj) => Object.assign(h, { [obj.key]:( h[obj.key] || [] ).concat(obj) }), {})