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);
1let 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);
1var cars = [
2 {
3 'make': 'audi',
4 'model': 'r8',
5 'year': '2012'
6 }, {
7 'make': 'audi',
8 'model': 'rs5',
9 'year': '2013'
10 }, {
11 'make': 'ford',
12 'model': 'mustang',
13 'year': '2012'
14 }, {
15 'make': 'ford',
16 'model': 'fusion',
17 'year': '2015'
18 }, {'make': 'kia', 'model': 'optima', 'year': '2012'},
19];
20
21result = cars.reduce((h, car) => Object.assign(h, { [car.make]:( h[car.make] || [] ).concat({model: car.model, year: car.year}) }), {})
22
23console.log(JSON.stringify(result));