p0l*_*Boy 22 javascript arrays algorithm search
var store = ['1','2','2','3','4'];
Run Code Online (Sandbox Code Playgroud)
我想知道2在数组中看起来最多.我该怎么做呢?
cod*_*ict 28
我会做的事情如下:
var store = ['1','2','2','3','4'];
var frequency = {}; // array of frequency.
var max = 0; // holds the max frequency.
var result; // holds the max frequency element.
for(var v in store) {
frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
if(frequency[store[v]] > max) { // is this frequency > max so far ?
max = frequency[store[v]]; // update max.
result = store[v]; // update result.
}
}
Run Code Online (Sandbox Code Playgroud)
arr.sort();
var max=0,result,freq = 0;
for(var i=0; i < arr.length; i++){
if(arr[i]===arr[i+1]){
freq++;
}
else {
freq=0;
}
if(freq>max){
result = arr[i];
max = freq;
}
}
return result;
Run Code Online (Sandbox Code Playgroud)
解决方案着重于Array.prototype.forEach,如果最大计数多个项目之间共享获得多于一个关键的问题。
编辑:只有一个循环的提案。
var store = ['1', '2', '2', '3', '4', '5', '5'],
distribution = {},
max = 0,
result = [];
store.forEach(function (a) {
distribution[a] = (distribution[a] || 0) + 1;
if (distribution[a] > max) {
max = distribution[a];
result = [a];
return;
}
if (distribution[a] === max) {
result.push(a);
}
});
console.log('max: ' + max);
console.log('key/s with max count: ' + JSON.stringify(result));
console.log(distribution);Run Code Online (Sandbox Code Playgroud)