Reputation: 4323
I'm having trouble grouping and then adding some values I get from JSON returned from an AJAX query.
The data comes back like this:
0: Object
count: 12
grp: 1
id: "1"
1: Object
count: 21
grp: 2
id: "3"
2: Object
count: 48
grp: 3
id: "4"
3: Object
count: 51
grp: 2
id: "5"
For grp
there are five possible options (groups): 1,2,3,4,5. What I want to do is add together all the count
values for each specific group. That is, add all grp
1 count
values together, all the grp
2 count
values together, and so on.
What's the best way to do this? I can't figure out an each
or anything that quite works.
Upvotes: 0
Views: 328
Reputation: 2356
var counts = {};
$.each(data, function(index, item){
var sum = counts[item.grp] || 0;
counts[item.grp] = sum + item.count;
});
console.log(counts);
# {1: 12, 2: 72, 3: 48}
Upvotes: 3