js group by
时间: 2023-11-21 08:57:08 浏览: 36
以下是两种JavaScript实现分组的方法:
1.使用reduce()方法实现分组
```javascript
const data = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'potato', type: 'vegetable' },
{ name: 'orange', type: 'fruit' },
{ name: 'broccoli', type: 'vegetable' },
];
const groupedData = data.reduce((result, item) => {
const key = item.type;
if (!result[key]) {
result[key] = [];
}
result[key].push(item);
return result;
}, {});
console.log(groupedData);
// 输出:
// {
// fruit: [
// { name: 'apple', type: 'fruit' },
// { name: 'banana', type: 'fruit' },
// { name: 'orange', type: 'fruit' }
// ],
// vegetable: [
// { name: 'carrot', type: 'vegetable' },
// { name: 'potato', type: 'vegetable' },
// { name: 'broccoli', type: 'vegetable' }
// ]
// }
```
2.使用自定义函数实现分组
```javascript
function groupBy(array, key) {
return array.reduce((result, item) => {
const group = item[key];
if (!result[group]) {
result[group] = [];
}
result[group].push(item);
return result;
}, {});
}
const data = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'potato', type: 'vegetable' },
{ name: 'orange', type: 'fruit' },
{ name: 'broccoli', type: 'vegetable' },
];
const groupedData = groupBy(data, 'type');
console.log(groupedData);
// 输出:
// {
// fruit: [
// { name: 'apple', type: 'fruit' },
// { name: 'banana', type: 'fruit' },
// { name: 'orange', type: 'fruit' }
// ],
// vegetable: [
// { name: 'carrot', type: 'vegetable' },
// { name: 'potato', type: 'vegetable' },
// { name: 'broccoli', type: 'vegetable' }
// ]
// }
```