Extracting the most duplicate value from an array in JavaScript (with jQuery)

前端 未结 5 1229
不思量自难忘°
不思量自难忘° 2020-12-01 17:26

I have several array to deal with. I need to extract the most duplicate value from each array.

From [3, 7, 7, 7], I need to find the value 7

5条回答
  •  被撕碎了的回忆
    2020-12-01 18:13

    Here's a quick example using javascript:

    function mostFrequent(arr) {
        var uniqs = {};
    
        for(var i = 0; i < arr.length; i++) {
            uniqs[arr[i]] = (uniqs[arr[i]] || 0) + 1;
        }
    
        var max = { val: arr[0], count: 1 };
        for(var u in uniqs) {
            if(max.count < uniqs[u]) { max = { val: u, count: uniqs[u] }; }
        }
    
        return max.val;
    }
    

    A quick note on algorithmic complexity -- because you have to look at each value in the array at least once, you cannot do better than O(n). This is assuming that you have no knowledge of the contents of the array. If you do have prior knowledge (e.g. the array is sorted and only contains 1s and 0s), then you can devise an algorithm with a run time that is some fraction of n; though technically speaking, it's complexity is still O(n).

提交回复
热议问题