3 回答
TA贡献1804条经验 获得超2个赞
您的方法意味着在-loop.indexOf()
的每次迭代中循环您的源数组(使用)。for(..
这将减慢不必要的查找过程。
相反,您可以使用Array.prototype.reduce()
遍历源数组并构建 ,将Map
所需Category
格式的键和对象作为值,然后提取Map.prototype.values()
到结果数组中。
这将执行得更快并且扩展性更好。
const src = [{App:"testa.com",Name:"TEST A",Category:"HR",Employees:7},{App:"testd.com",Name:"TEST D",Category:"DevOps",Employees:7},{App:"teste.com",Name:"TEST E",Category:"DevOps",Employees:7},{App:"testf.com",Name:"TEST F",Category:"Business",Employees:7}],
result = [...src
.reduce((r, {Category}) => {
const cat = r.get(Category)
cat ? cat.count ++ : r.set(Category, {Category, count: 1})
return r
}, new Map)
.values()
]
console.log(result)
.as-console-wrapper{min-height:100%;}
TA贡献1851条经验 获得超4个赞
最简单的方法是使用Array.prototype.reduce
const arr = [ ... ];
const output = arr.reduce((result, obj) => {
if (!result[obj.category]) {
result[obj.category] = 0;
}
result[obj.category]++;
return result;
}, {});
console.log(output); // this should log the similar output you want
TA贡献1784条经验 获得超7个赞
.map这是使用and的另一种选择Set:
const src = [
{
App: "testa.com",
Name: "TEST A",
Category: "HR",
Employees: 7
},
{
App: "testd.com",
Name: "TEST D",
Category: "DevOps",
Employees: 7
},
{
App: "teste.com",
Name: "TEST E",
Category: "DevOps",
Employees: 7
},
{
App: "testf.com",
Name: "TEST F",
Category: "Business",
Employees: 7
}
];
const categories = src.map(obj => obj.Category);
const distinctCategories = [...new Set(categories)];
console.log(distinctCategories.length);
添加回答
举报