JS实现Array.groupBy

现在,对产品列表执行一个简单的操作,将产品按类别分组。例如有如下数据,根据category字段进行分组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const products = [
{
name: "apples",
category: "fruits",
},
{
name: "oranges",
category: "fruits",
},
{
name: "potatoes",
category: "vegetable",
},
];

经过分组转换后的数据格式为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

{
"fruits": [
{
"name": "apples",
"category": "fruits"
},
{
"name": "oranges",
"category": "fruits"
}
],
"vegetable": [
{
"name": "potatoes",
"category": "vegetable"
}
]
}

下面总结了几种实现的方法:

通常的方法是使用 array.reduce()来实现,如下所示:

1
2
3
4
5
6
const groupByCategory = products.reduce((group, product) => {
const { category } = product;
group[category] = group[category] ?? [];
group[category].push(product);
return group;
}, {});

控制台打印结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"fruits": [
{
"name": "apples",
"category": "fruits"
},
{
"name": "oranges",
"category": "fruits"
}
],
"vegetable": [
{
"name": "potatoes",
"category": "vegetable"
}
]
}

控制台打印;

另外,如果项目中有引入lodash库的话,也可以直接使用groupBy方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { groupBy } from "lodash";

const products = [
{
name: "apples",
category: "fruits",
},
{
name: "oranges",
category: "fruits",
},
{
name: "potatoes",
category: "vegetable",
},
];

console.log(groupBy(products, "category"));

效果也是一样的可以实现.