JavaScript 最近发布了一个方法 Object.groupBy,可以对可迭代对象中的元素进行分组。
语法:
Object.groupBy(items, callbackFn)
items
被分组的可迭代对象,如 Array。
callbackFn
对可迭代对象中的每个元素执行的函数。
举个例子,我们想要根据城市的首字符进行分组:
const cityList = [
{ id: 1, name: "beijing" },
{ id: 2, name: "shanghai" },
{ id: 3, name: "guangzhou" },
{ id: 4, name: "shenzhen" },
{ id: 5, name: "hangzhou" },
{ id: 6, name: "chengdu" },
{ id: 7, name: "wuhan" },
{ id: 8, name: "xian" },
{ id: 9, name: "chongqing" },
];
const result = Object.groupBy(cityList, (city) => city.name[0]);
返回结果:
{
"b": [
{
"id": 1,
"name": "beijing"
}
],
"s": [
{
"id": 2,
"name": "shanghai"
},
{
"id": 4,
"name": "shenzhen"
}
],
"g": [
{
"id": 3,
"name": "guangzhou"
}
],
"h": [
{
"id": 5,
"name": "hangzhou"
}
],
"c": [
{
"id": 6,
"name": "chengdu"
},
{
"id": 9,
"name": "chongqing"
}
],
"w": [
{
"id": 7,
"name": "wuhan"
}
],
"x": [
{
"id": 8,
"name": "xian"
}
]
}