Counting the occurrences / frequency of array elements

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

    One line ES6 solution. So many answers using object as a map but I can't see anyone using an actual Map

    const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
    

    Use map.keys() to get unique elements

    Use map.values() to get the occurrences

    Use map.entries() to get the pairs [element, frequency]

    var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]
    
    const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
    
    console.info([...map.keys()])
    console.info([...map.values()])
    console.info([...map.entries()])

提交回复
热议问题