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
1function groupByKey(array, key) {
2 return array
3 .reduce((hash, obj) => {
4 if(obj[key] === undefined) return hash;
5 return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
6 }, {})
7}
8
9
10var 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'}];
11
12var result = groupByKey(cars, 'make');
13
14JSON.stringify(result,"","\t");
15{
16 "audi": [
17 {
18 "make": "audi",
19 "model": "r8",
20 "year": "2012"
21 },
22 {
23 "make": "audi",
24 "model": "rs5",
25 "year": "2013"
26 }
27 ],
28 "ford": [
29 {
30 "make": "ford",
31 "model": "mustang",
32 "year": "2012"
33 },
34 {
35 "make": "ford",
36 "model": "fusion",
37 "year": "2015"
38 }
39 ],
40 "kia": [
41 {
42 "make": "kia",
43 "model": "optima",
44 "year": "2012"
45 }
46 ]
47}
1var results = orgs.reduce(function(results, org) {
2 (results[org.id] = results[org.id] || []).push(org);
3 return results;
4}, {})
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);