How to return count of objects from an array using JavaScript ES5

I have the below array of objects.

var arr = [
{group: “AA”, complexity: “Simple”},
{group: “AA”, complexity: “Complex”},
{group: “AA”, complexity: “Simple”},
{group: “BB”, complexity: “Simple”},
{group: “AA”, complexity: “Medium”}
];

I am trying to get the below as the output:

[
{group: “AA”, complexity: “Simple”,count: 2},
{group: “AA”, complexity: “Complex”,count: 1},
{group: “BB”, complexity: “Simple”,count: 1},
{group: “AA”, complexity: “Medium”,count: 1}
]

Can anyone please help me achieve this?

Not sure you can use an object as the key in another object. You could make something that looks like this, though:

[

{group: “AA”, complexity: “Simple”, count: 2},
{group: “AA”, complexity: “Complex”,count: 1},
{group: “BB”, complexity: “Simple”, count: 1},
{group: “AA”, complexity: “Medium”,count: 1}
]

And with ES5, the cleanest way might be to write a reducer function. If you Google something like “using reduce to group objects” there are some great articles that might help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.