分组数组并计数基于JavaScript中的组创建新数组的项目
假设我们有一个像这样的对象数组-
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函数。该函数应准备一个新的对象数组,该对象数组将根据对象的“area”属性对数据进行分组。
该功能还应保留特定区域的唯一用户数。
因此,对于上述数组,输出应类似于-
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 }
]