手动实现
- 使用
reduce
方法实现 groupBy
函数来实现将数组中的元素根据某个属性或条件分组
const groupBy = (array, key) => {
return array.reduce((result, element) => {
const groupKey = key(element);
if (!result[groupKey]) {
result[groupKey] = [];
}
result[groupKey].push(element);
return result;
}, {});
};
const people = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 20 },
{ name: 'Jim', age: 30 },
{ name: 'Joan', age: 30 }
];
const peopleByAge = groupBy(people, person => person.age);
console.log(peopleByAge);
{
'20': [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 20 }
],
'30': [
{ name: 'Jim', age: 30 },
{ name: 'Joan', age: 30 }
]
}
原生支持 Object.groupBy
ECMAScript 2024(ES15)
提案已加入 Object.groupBy
方法
- 注意目前需要谷歌浏览器
117
以上的版本才能运行
const people = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 20 },
{ name: 'Jim', age: 30 },
{ name: 'Joan', age: 30 }
];
const peopleByAge = Object.groupBy(people, person => person.age);
console.log(peopleByAge);
{
'20': [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 20 }
],
'30': [
{ name: 'Jim', age: 30 },
{ name: 'Joan', age: 30 }
]
}