1const users = [{
2 name: "Jim",
3 color: "blue"
4 },
5 {
6 name: "Sam",
7 color: "blue"
8 },
9 {
10 name: "Eddie",
11 color: "green"
12 },
13 {
14 name: "Robert",
15 color: "green"
16 },
17];
18const groupBy = (arr, key) => {
19 const initialValue = {};
20 return arr.reduce((acc, cval) => {
21 const myAttribute = cval[key];
22 acc[myAttribute] = [...(acc[myAttribute] || []), cval]
23 return acc;
24 }, initialValue);
25};
26
27const res = groupBy(users, "color");
28console.log("group by:", res);