JavaScript code to get count of occurrence of obje

2019-07-12 02:20发布

问题:

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]

回答1:

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



回答2:

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}