How to count Matching values in Array of Javascript

前端 未结 4 911
死守一世寂寞
死守一世寂寞 2020-12-04 04:18

please tell me any good algorithm/code to get list of unique values from array and count of its occurrence in array. (i am using javascript).

4条回答
  •  时光说笑
    2020-12-04 04:34

    a straightforward way is to loop over the array once and count values in a hash

    a = [11, 22, 33, 22, 11];
    count = {}
    for(var i = 0; i < a.length; i++)
       count[a[i]] = (count[a[i]] || 0) + 1
    

    the "count" would be like this { 11: 2, 22: 2, 33: 1 }

    for sorted array the following would be faster

    a = [11, 11, 11, 22, 33, 33, 33, 44];
    a.sort()
    uniq = [];
    len = a.length
    for(var i = 0; i < len;) {
       for(var k = i; k < len && a[k] == a[i]; k++);
       if(k == i + 1) uniq.push(a[i])
       i = k
    }   
    // here uniq contains elements that occur only once in a
    

提交回复
热议问题