Counting the occurrences / frequency of array elements

前端 未结 30 2568
甜味超标
甜味超标 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:33

    You can use an object to hold the results:

    var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
    var counts = {};
    
    for (var i = 0; i < arr.length; i++) {
      var num = arr[i];
      counts[num] = counts[num] ? counts[num] + 1 : 1;
    }
    
    console.log(counts[5], counts[2], counts[9], counts[4]);

    So, now your counts object can tell you what the count is for a particular number:

    console.log(counts[5]); // logs '3'
    

    If you want to get an array of members, just use the keys() functions

    keys(counts); // returns ["5", "2", "9", "4"]
    

提交回复
热议问题