var store = ['1','2','2','3','4'];
我想找出
2
在数组中出现得最多。我该怎么做呢? 最佳答案
我会做类似的事情:
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.
}
}
关于javascript - 获取数组中出现次数最多的项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3783950/