Counting the occurrences / frequency of array elements

前端 未结 30 2129
甜味超标
甜味超标 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条回答
  •  梦毁少年i
    2020-11-21 07:30

    If using underscore or lodash, this is the simplest thing to do:

    _.countBy(array);
    

    Such that:

    _.countBy([5, 5, 5, 2, 2, 2, 2, 2, 9, 4])
    => Object {2: 5, 4: 1, 5: 3, 9: 1}
    

    As pointed out by others, you can then execute the _.keys() and _.values() functions on the result to get just the unique numbers, and their occurrences, respectively. But in my experience, the original object is much easier to deal with.

提交回复
热议问题