var developers = [
{ name: "Joe", age: 23 ,overallLevel: "high"},
{ name: "Sue", age: 28 ,overallLevel: "advanced" },
{ name: "Jon", age: 32 ,overallLevel: "high" },
{ name: "Bob", age: 24 ,overallLevel: "high" },
{ name: "Bob", age: 20 ,overallLevel: "advanced" }
]
需要使用array.reduce()在上述数组中对totalLevel进行计数
[高:3,进阶:2]
最佳答案
您可以将它们与一个对象一起计数。
var developers = [{ name: "Joe", age: 23, overallLevel: "high" }, { name: "Sue", age: 28, overallLevel: "advanced" }, { name: "Jon", age: 32, overallLevel: "high" }, { name: "Bob", age: 24, overallLevel: "high" }, { name: "Bob", age: 20, overallLevel: "advanced" }],
overallLevel = developers.reduce(function (r, a) {
r[a.overallLevel] = (r[a.overallLevel] || 0) + 1;
return r;
}, {});
console.log(overallLevel);