Jquery计算数组中出现的次数

时间:2014-03-21 11:26:54

标签: jquery

我想计算数组中每个元素的数量

示例:

 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

 }

然后我想输出

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

提前致谢

2 个答案:

答案 0 :(得分:7)

您可以尝试:

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

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

结果:

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

答案 1 :(得分:3)

尝试

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);

输出

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

Live Demo