Counting the occurrences / frequency of array elements

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

    ES6 version should be much simplifier (another one line solution)

    let arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
    let acc = arr.reduce((acc, val) => acc.set(val, 1 + (acc.get(val) || 0)), new Map());
    
    console.log(acc);
    // output: Map { 5 => 3, 2 => 5, 9 => 1, 4 => 1 }
    

    A Map instead of plain Object helping us to distinguish different type of elements, or else all counting are base on strings

提交回复
热议问题