一尘不染

获取数组中出现次数最多的项目

algorithm

var store = ['1','2','2','3','4'];

我想找出2在阵列中出现最多的东西。我该怎么做呢?


阅读 199

收藏
2020-07-28

共1个答案

一尘不染

我会做类似的事情:

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.
        }
}
2020-07-28