array_count_values for JavaScript instead

前端 未结 6 1582
情歌与酒
情歌与酒 2020-12-10 20:04

I have the following PHP-script, now I need to do the same thing in JavaScript. Is there a function in JavaScript that works similar to the PHP function, I have been searchi

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 20:48

    Why not simply create a new javascript array "counts" Iterate over original array, and increament the count of "counts" for keys encountered in the array. http://jsfiddle.net/4t28P/1/

    var myCurrentArray = new Array("apple","banana","apple","orange","banana","apple");
    
    var counts = {};
    
    for(var i=0;i< myCurrentArray.length;i++)
    {
      var key = myCurrentArray[i];
      counts[key] = (counts[key])? counts[key] + 1 : 1 ;
    
    }
    
    alert(counts['apple']);
    alert(counts['banana']);
    

提交回复
热议问题