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

2023-09-11 01:49:15 作者:乘着风的人

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

我想找出 2 出现在最到数组中。我该如何去这样做?

I want to find out that 2 appear the most in the array. How do I go about doing that?

推荐答案

我会做这样的事情:

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