- 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
- 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