对数组进行分组并计算项目数,基于 JavaScript 中的组创建新数组
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 19:24:17
假设,我们有一个像这样的对象数组 −
const arr = [
{ region: "Africa", fruit: "Orange", user: "Gary" },
{ region: "Africa", fruit: "Apple", user: "Steve" },
{ region: "Europe", fruit: "Orange", user: "John" },
{ region: "Europe", fruit: "Apple", user: "bob" },
{ region: "Asia", fruit: "Orange", user: "Ian" },
{ region: "Asia", fruit: "Apple", user: "Angelo" },
{ region: "Africa", fruit: "Orange", user: "Gary" }
];
我们需要编写一个 JavaScript 函数来接收一个这样的数组。该函数应准备一个新的对象数组,该数组基于"区域"对数据进行分组对象的属性。
该函数还应保留特定区域的唯一用户数量。
因此,对于上述数组,输出应如下所示 −
const output = [
{
"region": "Africa",
"count": 2
},
{
"region": "Europe",
"count": 2
},
{
"region": "Asia",
"count": 2
}
];
示例
其代码为 −
const arr = [
{ region: "Africa", fruit: "Orange", user: "Gary" },
{ region: "Africa", fruit: "Apple", user: "Steve" },
{ region: "Europe", fruit: "Orange", user: "John" },
{ region: "Europe", fruit: "Apple", user: "bob" },
{ region: "Asia", fruit: "Orange", user: "Ian" },
{ region: "Asia", fruit: "Apple", user: "Angelo" },
{ region: "Africa", fruit: "Orange", user: "Gary" }
];
const groupByArea = (arr = []) => {
const res = [];
arr.forEach(el => {
let key = [el.region, el.user].join('|');
if (!this[el.region]) {
this[el.region] = { region: el.region, count: 0 };
res.push(this[el.region]);
};
if (!this[key]) {
this[key] = true;
this[el.region].count++;
};
}, Object.create(null));
return res;
}
console.log(groupByArea(arr));
输出
控制台中的输出将是 −
[
{ region: 'Africa', count: 2 },
{ region: 'Europe', count: 2 },
{ region: 'Asia', count: 2 }
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

