Counting the occurrences / frequency of array elements

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

    Based on answer of @adamse and @pmandell (which I upvote), in ES6 you can do it in one line:

    • 2017 edit: I use || to reduce code size and make it more readable.

    var a=[7,1,7,2,2,7,3,3,3,7,,7,7,7];
    alert(JSON.stringify(
    
    a.reduce((r,k)=>{r[k]=1+r[k]||1;return r},{})
    
    ));


    It can be used to count characters:

    var s="ABRACADABRA";
    alert(JSON.stringify(
    
    s.split('').reduce((a, c)=>{a[c]++?0:a[c]=1;return a},{})
    
    ));

提交回复
热议问题