Home >Web Front-end >JS Tutorial >How to find the most repeated element in an array

How to find the most repeated element in an array

一个新手
一个新手Original
2017-09-27 10:35:436546browse

Start my blogging career

---------------------------------- ------------------Warn yourself

Title: The most repeated element in the array

Without further ado, let’s go straight to the code- ------

First method:

function getMost(arr){
	var hash = {};
	var m = 0; 
	var trueEl;
	var el;
	for(var i = 0,len = arr.length; i < len; i++ ) {
	el = arr[i];
	hash[el] === undefined ? hash[el] = 1 : (hash[el] ++);
	if(hash[el] >= m){
		m = hash[el];
		trueEl = el; 
	}
	}
	return trueEl;
};    	

Second method:

function getMost(arr) {
	if (!arr.length) return
	if (arr.length === 1) return 1
	var res = {}
	// 遍历数组
	for (var i=0,l=arr.length;i<l;i++) {
		if (!res[arr[i]]) {
			res[arr[i]] = 1;
		} else {
			res[arr[i]]++;
		}
	}
	// 遍历 res
	var keys = Object.keys(res);
	console.log(keys);
	var maxNum = 0, maxEle;
	for (var i=0,l = keys.length;i<l;i++) {
	if (res[keys[i]] > maxNum) {
		maxNum = res[keys[i]];
		maxEle = keys[i];
	}
	 return maxEle;
}

Third method:

Array.prototype.getMost = function(){
	var obj = this.reduce((p,n) =>(p[n]++ ||(p[n] = 1),(p.max=p.max>=p[n]?p.max:p[n]), (p.key=p.max>p[n]?p.key:n), p), {});
	return &#39;key: &#39;+ obj.key+ &#39; len: &#39;+obj.max;}
var arr = [1,2,3,4,2,1,4,2,3,5];
arr.getMost();

Third method There is a bug in this method. If there are multiple elements with the highest number of repetitions, the last element will be returned.

The above is the detailed content of How to find the most repeated element in an array. For more information, please follow other related articles on the PHP Chinese website!

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