JavaScript fun: Find the element with the maximum frequency of array appearance

Source: Internet
Author: User
Given an array, pass it into a highestRank (arr) function, and return the element with the highest frequency in the array. 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 maximum frequency, the element with the maximum number is returned.

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 kind of appearance frequency, we 'd better make a statistical statement to see how often each number appears.


Then, select the one with the most frequent appearance, or the number of groups.

Finally, find the largest number from the number and return it.

I personally prefer to use hash objects for efficient and easy enumeration.

Sorting can also be solved, but the efficiency is certainly lower.

function highestRank(arr){      var hash = {};      var highest = 0;      var highestArray = [];      for(var i=0;i 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 JavaScript fun: Find the content of the element with the highest frequency of appearance in the array. For more information, see the PHP Chinese Network (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.