Counting the occurrences / frequency of array elements

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

    Here you go:

    Live demo: http://jsfiddle.net/simevidas/bnACW/

    Note

    This changes the order of the original input array using Array.sort

    var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];
    
    function foo(arr) {
      var a = [],
        b = [],
        prev;
    
      arr.sort();
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] !== prev) {
          a.push(arr[i]);
          b.push(1);
        } else {
          b[b.length - 1]++;
        }
        prev = arr[i];
      }
    
      return [a, b];
    }
    
    var result = foo(arr);
    console.log('[' + result[0] + ']','[' + result[1] + ']')

提交回复
热议问题