获取出现次数最多的一个数组中的项目 [英] Get the item that appears the most times in an array

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

问题描述

var store = ['1','2','2','3','4'];

我想找出 2 出现在最到数组中。我该如何去这样做?

I want to find out that 2 appear the most in the array. How do I go about doing that?

推荐答案

我会做这样的事情:

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.
        }
}

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

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