获取数组中出现次数最多的元素 [英] Get the element with the highest occurrence in an array

查看:513
本文介绍了获取数组中出现次数最多的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

例如,在

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

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

the 'apple' element is the most frequent one.

推荐答案

这只是模式。这是快速,非优化的解决方案。它应该是O(n)。

This is just the mode. Here's a quick, non-optimized solution. It should be 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;
}

这篇关于获取数组中出现次数最多的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆