gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:17:04 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com