📅  最后修改于: 2022-03-11 15:02:56.777000             🧑  作者: Mango
const users = [{
name: "Jim",
color: "blue"
},
{
name: "Sam",
color: "blue"
},
{
name: "Eddie",
color: "green"
},
{
name: "Robert",
color: "green"
},
];
const groupBy = (arr, key) => {
const initialValue = {};
return arr.reduce((acc, cval) => {
const myAttribute = cval[key];
acc[myAttribute] = [...(acc[myAttribute] || []), cval]
return acc;
}, initialValue);
};
const res = groupBy(users, "color");
console.log("group by:", res);