I am trying to calculate all the huishoudens that are in each provincie. For this question I created a fiddle which can be found here: http://jsfiddle.net/Lyf1sak3/1/
With this sample data:
<div data-provincie="Noord-Holland" data-huishoudens="102"></div>
<div data-provincie="Noord-Holland" data-huishoudens="1250"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="956"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="235"></div>
<div data-provincie="Groningen" data-huishoudens="495"></div>
<div data-provincie="Groningen" data-huishoudens="55"></div>
<div data-provincie="Groningen" data-huishoudens="247"></div>
<div data-provincie="Utrecht" data-huishoudens="123"></div>
<div data-provincie="Utrecht" data-huishoudens="675"></div>
And this code:
var provincies = {},
provincie;
sum = 0;
$('*[data-provincie]').each(function(i, el){
provincie = $(el).data('provincie');
if (provincies.hasOwnProperty(provincie)) {
provincies[provincie] += 1;
sum += $(this).data('huishoudens');
}
else {
provincies[provincie] = 1;
}
});
// print results
$('#result').append('<hr>');
for(var key in provincies){
$('#result').append(key + ' (' + provincies[key] + '|' + sum + ')<br>');
}
I am grouping each provincie by its own property and now I just need to calculate the other data attribute, but I am completely stuck here. I am getting either the result 675 which is the last div in the sample data or I get 2462 and I have no clue how it gets that number.
What do I need to modify to get this result:
Noord-Holland (2|1352)
Zuid-Holland (2|1191)
Groningen (3|797)
Utrecht (2|798)
Whatever answer you give it is really appreciated but please don't post answers where it requires to hard code the names of provincie like $('*[data-provincie="Noord-Holland"]');