Learn to find the most repeated elements in an array and count the number of repetitions

Source: Internet
Author: User

    1. Through JSON, the values in the array are passed to the keys in the JSON, using the keys in the JSON is not repeatable performance, and if you encounter duplicate keys, let the value of the key increment by 1, so that the number of repetitions can be counted
    2. The above method can draw a JSON, but not enough, because the key or value in the JSON cannot be compared to the size of the JSON, each set of data will be made into a small JSON into an array, the number of statistics assigned to each value in the JSON, Sorting by using the Sort comparison function of the array
function myMaxElement(arr){ var json = {};  for (varI=0;I<arr.length;I++) { if   ( json  [ arr  Span style= "color: #93a1a1; Font-weight:bold; " >[ i   Span style= "color: #ea7500; Font-weight:bold; " >//This idea is very important, in the array of elements into the JSON when the key to determine whether the JSON has already appeared, if not, let the key is assigned a value of 1, if it already appears, let its value increment by 1   json[arr[i]]++; }else{ json  [< /span>arr  [ i  ]   =  1    } } var   NEWARR  =  [];   for   ( var   name  in   JSON  ) {  var   Newjson  =  {};   Newjson   . a  =   name   //Loop JSON, passing the keys of each set of data to a new JSON, the value passed to the new JSON B   Newjson   . b  =   JSON  [ name  ]; newArr.push(newJson);//再将这个新json添加到新数组中,这样新数组中都是一个个小json,每个json都有2组元素,它们的键分别是a和b }   NEWARR   sort   ( function   ( n1   n2  ){ return   N1  . b  -  N2   b   //sorts each small JSON by comparison function, comparing the size of B in each small JSON   }); returnNEWARR[NEWARR.length-1].a+ ': ' +NEWARR[NEWARR.length-1].b; //Get the most occurrences of the key, and the number of times it appears}vararr= [1,4,5,6,3,4,6,6,6,4,6,6,4,3,2,3,4,5,3,4,7,8,9,7,8,6,5,4];console.log(myMaxElement(arr));

Learn to find the most repeated elements in an array and count the number of repetitions

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.