【问题标题】:Jquery Count number of occurances in array [duplicate]Jquery计数数组中出现的次数[重复]
【发布时间】:2014-03-21 11:26:53
【问题描述】:

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

例子:

 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

提前致谢

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你可以试试:

    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}
    

    【讨论】:

      【解决方案2】:

      试试

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 2012-11-18
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        相关资源
        最近更新 更多