var store = ['1','2','2','3','4'];
我想找出 2
在数组中出现最多的。我该怎么做呢?
原文由 p0larBoy 发布,翻译遵循 CC BY-SA 4.0 许可协议
var store = ['1','2','2','3','4'];
我想找出 2
在数组中出现最多的。我该怎么做呢?
原文由 p0larBoy 发布,翻译遵循 CC BY-SA 4.0 许可协议
重点解决 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 许可协议
13 回答13.1k 阅读
7 回答2.3k 阅读
3 回答1.4k 阅读✓ 已解决
6 回答1.5k 阅读✓ 已解决
2 回答1.5k 阅读✓ 已解决
3 回答1.5k 阅读✓ 已解决
6 回答1.2k 阅读
我会做类似的事情: