Counting the occurrences / frequency of array elements

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

    Don't use two arrays for the result, use an object:

    a      = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
    result = { };
    for(var i = 0; i < a.length; ++i) {
        if(!result[a[i]])
            result[a[i]] = 0;
        ++result[a[i]];
    }
    

    Then result will look like:

    {
        2: 5,
        4: 1,
        5: 3,
        9: 1
    }
    

提交回复
热议问题