对数组进行分组和统计项目,根据 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 } ]
广告