Counting the occurrences / frequency of array elements

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

    I know this question is old but I realized there are too few solutions where you get the count array as asked with a minimal code so here is mine

    // The initial array we want to count occurences
    var initial = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];  
    
    // The count array asked for
    var count = Array.from(new Set(initial)).map(val => initial.filter(v => v === val).length);  
    
    // Outputs [ 3, 5, 1, 1 ]
    

    Beside you can get the set from that initial array with

    var set = Array.from(new Set(initial));  
    
    //set = [5, 2, 9, 4]  
    

提交回复
热议问题