0

I have an array of items.

var items = {'A', 'A', 'A', 'B', 'B', 'C'}

I want to output an array that counts how many of each item there is. So the output should look like:

{
  'A': 3,
  'B': 2,
  'C': 1

}    
p101xc
  • 11
  • 1

2 Answers2

0

The biggest reason why it isn't working is that using {} means that you are declaring an object, using [] means you are declaring an array.

Other than that, the code you wrote requires very little modification

var items = ['A', 'A', 'A', 'B', 'B', 'C'];

function count(items) {
    var result = [];
    var count = 0; 
    for (var i=0; i<items.length; i++) {
       var item = items[i];


       if(typeof result[item] === 'undefined') {
           //this is the first time we have encountered this key
           //so we initialize its count to 0
           result[item] = 0;
       }

       result[item]++; 
   }

   return result;
}

var result = count(items);
for (var key in result) {
    alert(key + " : " + result[key]);
}
spectacularbob
  • 3,080
  • 2
  • 20
  • 41
0

If you have an array [] instead of an object {} this works:

var items = ['A', 'A', 'A', 'B', 'B', 'C'];
var o = {}; 
items.forEach(function(element) {
  (element in o) ? o[element]++ : o[element] = 1;  
});

If you have a real object with keys and values you could use Object.keys() on items to return an array.

John Estess
  • 576
  • 10
  • 22