How to count Matching values in Array of Javascript

前端 未结 4 910
死守一世寂寞
死守一世寂寞 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:55

    Use an object as an associative array:

    var histo = {}, val;
    for (var i=0; i < arr.length; ++i) {
        val = arr[i];
        if (histo[val]) {
            ++histo[val];
        } else {
            histo[val] = 1;
        }
    }
    

    This should be at worst O(n*log(n)), depending on the timing for accessing object properties. If you want just the strings, loop over the object's properties:

    for (val in histo) {...}
    

提交回复
热议问题