gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:51:27 36 4
gpt4 key购买 nike

我正在寻找一种优雅的方法来确定哪个元素在 JavaScript 数组中出现次数最多 ( mode )。

例如,在

['pear', 'apple', 'orange', 'apple']

'apple' 元素是最常见的元素。

最佳答案

这只是模式。这是一个快速、未优化 的解决方案。应该是O(n)。

function mode(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}

关于javascript - 获取数组中出现次数最多的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1053843/

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