-3

I have a JSON array, obviously. And I'm stuck in JS (no JQuery).

I have to find each distinct value for 'Service' and the count of each value.

So, if 100 shows up 3 times and 101 shows up 5 times, I need my result to be something like:

{ "100" : "3", "101" : "5"}

and I'd rather not use a regular loop if there's something more concise I can use like forEach()

Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56

2 Answers2

3

First of all, convert your JSON array to an array object:

var json_ar = '[100, 100, 101, 100, 101, 101, 101, 101]';
var ar = JSON.parse(json_ar);

From then on, it's simply counting, which depends a little bit on what the objects in your array actually are. If they're numbers, a simplistic

var counts = {};
ar.forEach(function(v) {
    counts[v] = counts[v] ? counts[v] + 1 : 1;
});

will get you counts = {'100': 3, '101': 5}.

Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
0

If you're not as fond of <array>.forEach(<callback>) you could also use a normal for..of loop:

var result = {};
for (var val of json_object) result[val] = result[val] ? result[val] + 1 : 1;
Chiri Vulpes
  • 478
  • 4
  • 18