6

I'd like to count the number of each element in my array

Example:

 var basketItems = ['1','3','1','4','4'];

 jQuery.each(basketItems, function(key,value) {

 // Go through each element and tell me how many times it occurs, output this and remove duplicates

 }

I'd then like to output

Item  |  Occurances
--------------------
1     |  2
3     |  1
4     |  2

Thanks in advance

Corbin Spicer
  • 285
  • 1
  • 8
  • 26

2 Answers2

10

You can try with:

var basketItems = ['1','3','1','4','4'],
    counts = {};

jQuery.each(basketItems, function(key,value) {
  if (!counts.hasOwnProperty(value)) {
    counts[value] = 1;
  } else {
    counts[value]++;
  }
});

Result:

Object {1: 2, 3: 1, 4: 2}
hsz
  • 148,279
  • 62
  • 259
  • 315
3

Try

var basketItems = ['1','3','1','4','4'];
var returnObj = {};

$.each(basketItems, function(key,value) {

var numOccr = $.grep(basketItems, function (elem) {
    return elem === value;
}).length;
    returnObj[value] = numOccr
});
console.log(returnObj);

output:

Object { 1=2, 3=1, 4=2}

Live Demo

Rajesh Dhiman
  • 1,888
  • 1
  • 17
  • 30