JavaScript code to get count of occurrence of obje

2019-07-12 02:11发布

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" }
]

Need count of overallLevel in the mentioned array using array.reduce() [high:3, advanced:2]

2条回答
我想做一个坏孩纸
2楼-- · 2019-07-12 02:56

You could just count them with an object.

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);

查看更多
狗以群分
3楼-- · 2019-07-12 02:57

Try this (you need no array.reduce() to do that):

var
  i,
  count = {high: 0, advanced: 0},
  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" }
  ];

for (i in developers) {

  count[developers[i].overallLevel]++;
}

alert(JSON.stringify(count)); //  Object { high=3,  advanced=2}

查看更多
登录 后发表回答