I'm trying to count similar array values to get how many quantities of similar items there are in array. I managed to get the counts however I want to show every quantities in the array in HTML
var arr = ['Coke','Coke Diet','Pepsi','Sprite','Coke','Water'];
var obj = [];
for (var i = 0, j = arr.length; i < j; i++) {
if (obj[arr[i]]) {
obj[arr[i]]++;
}
else {
obj[arr[i]] = 1;
}
}
I'm having a problem to render them in HTML without specifying what type of drink.
$('#items').append(obj.Coke)
How can I .append(obj) without saying what kind of drink I want to show?
I want to show something like -- (quantity) (drink)
2x Coke
1x Sprite
3x Water
Edit -- both answers below works, but I have another question regarding this. How can I prevent rendering the same item when adding an item to array instead just want to update the quantity when you hit add button.
I've created a new fiddle for this follow up question.
End Result should look like --
1 Coke
2 Sprite
rather than
1 Coke
1 Sprite
2 Sprite
var obj = [];should bevar obj = {};obj.Cokeobj?obj['Coke']- so just iterate thru the keys and pass that value in to the obj -obj[key]wherekey = 'Coke'. Also see the answer added below