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]

Saily Jadhav
  • 149
  • 2
  • 10
  • 1
    What have you tried already? What issues are you facing? Generally speaking `Fix this for me` questions don't go down too well. – ste2425 Jun 01 '16 at 10:18
  • https://jsfiddle.net/rdw26c3k/ – adeneo Jun 01 '16 at 10:20
  • You could use filter() and just pass value of overallLevel to filter by. Than you could just count items in filtered array. – Nemanja Todorovic Jun 01 '16 at 10:21
  • Possible duplicate of [Find the number of occurrences a given value has in an array](http://stackoverflow.com/questions/17313268/find-the-number-of-occurrences-a-given-value-has-in-an-array) – 1983 Jun 01 '16 at 10:54
  • 1
    please have a look to [What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answers) – Nina Scholz Jun 01 '16 at 12:04

2 Answers2

7

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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}
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47