3
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]

5

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Could you tell us how (r[a.overallLevel] || 0) + 1; will evaluate
@SandeepNayak r[a.overallLevel] || 0 will assign zero should r[a.overallLevel] be a fasly value. It will then add one to it.
3

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.