Home  >  Article  >  Web Front-end  >  Interesting JavaScript question: Find the element with the maximum frequency of occurrence in an array

Interesting JavaScript question: Find the element with the maximum frequency of occurrence in an array

黄舟
黄舟Original
2017-02-04 15:45:051507browse

Given an array, pass it into a highestRank(arr) function, and return the element with the highest frequency in the array.

If there are multiple elements with the highest frequency of occurrence, return the one with the largest value.

For example:

arr = [12, 10, 8, 12, 7, 6, 4, 10, 12];  
highestRank(arr) //=> returns 12  
  
arr = [12, 10, 8, 12, 7, 6, 4, 10, 12, 10];  
highestRank(arr) //=> returns 12  
  
arr = [12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10];  
highestRank(arr) //=> returns 3

For this type of frequency calculation, it is best to make statistics to see how often each number appears.


Next, filter out the one with the highest frequency, or a group of numbers.

Finally, find the largest one from this set of numbers and return it.

I personally prefer to use hash objects to solve the problem, which is efficient and easy to enumerate.

Sorting can also be solved, but the efficiency will definitely be lower

function highestRank(arr){  
    var hash = {};  
    var highest = 0;  
    var highestArray = [];  
    for(var i=0;i<arr.length;i++){  
        var cur = arr[i];  
        if(hash[cur]){  
            hash[cur] = 1 + hash[cur];  
        }  
        else{  
            hash[cur] = 1;  
        }  
        if(hash[cur] > highest){  
            highest = hash[cur];  
        }  
    }  
    for(var j in hash){  
        if(hash.hasOwnProperty(j)){  
            if(hash[j] === highest){  
                highestArray.push(j);  
            }  
        }  
    }  
    return Math.max.apply(null,highestArray);  
}

The above is an interesting JavaScript question: find the content of the element with the largest frequency of occurrence in an array. For more related content, please pay attention to the PHP Chinese website ( www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn