Counting the occurrences / frequency of array elements

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

    function countOcurrences(arr){
        return arr.reduce((aggregator, value, index, array) => {
          if(!aggregator[value]){
            return aggregator = {...aggregator, [value]: 1};  
          }else{
            return aggregator = {...aggregator, [value]:++aggregator[value]};
          }
        }, {})
    }
    

提交回复
热议问题