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

新手上路,请多包涵
var store = ['1','2','2','3','4'];

我想找出 2 在数组中出现最多的。我该怎么做呢?

原文由 p0larBoy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 268
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.
        }
}

原文由 codaddict 发布,翻译遵循 CC BY-SA 2.5 许可协议

重点解决 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);

原文由 Nina Scholz 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题