Counting the occurrences / frequency of array elements

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

    If you favour a single liner.

    arr.reduce(function(countMap, word) {countMap[word] = ++countMap[word] || 1;return countMap}, {});

    Edit (6/12/2015): The Explanation from the inside out. countMap is a map that maps a word with its frequency, which we can see the anonymous function. What reduce does is apply the function with arguments as all the array elements and countMap being passed as the return value of the last function call. The last parameter ({}) is the default value of countMap for the first function call.

提交回复
热议问题