Counting the occurrences / frequency of array elements

前端 未结 30 2168
甜味超标
甜味超标 2020-11-21 06:47

In Javascript, I\'m trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each

30条回答
  •  孤街浪徒
    2020-11-21 07:34

    Here's just something light and easy for the eyes...

    function count(a,i){
     var result = 0;
     for(var o in a)
      if(a[o] == i)
       result++;
     return result;
    }
    

    Edit: And since you want all the occurences...

    function count(a){
     var result = {};
     for(var i in a){
      if(result[a[i]] == undefined) result[a[i]] = 0;
      result[a[i]]++;
     }
     return result;
    }
    

提交回复
热议问题