I'm trying to loop through an array in order to group and count totals.
For example:
var farm = [['Cats', 3], ['Cats', 4], ['Mice', 2], ['Dogs', 5]];
I would like to go through and first see 'Cats', then add all the cat values up, then repeat the process for other unique categories.
The final output would be:
Cats (7)
Mice (2)
Dogs (5)
Currently, I'm trying to accomplish it this way, but I'm obviously making a rookie mistake somewhere.
var farm = [];
farm.push(['Cats', 3], ['Cats', 4], ['Mice', 2], ['Dogs', 5]);
var animalCounter = function(array){
var list = '';
for(var i = 0; i<array.length; i++){
var animalID = array[i][0];
var animalCount = 0;
for (var x; x<array.length; x++){
if(animalID == array[x][0]){
animalCount += array[x][0] - 1;
}
list += animalID + " (" + animalCount + ")\n";
}
}
alert(list);
}
animalCounter(farm);