Home > Web Front-end > JS Tutorial > 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

黄舟
Release: 2017-02-04 15:45:05
Original
1526 people have browsed it

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
Copy after login

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);  
}
Copy after login

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 ( m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template