获取数组中出现次数最多的项 [英] Get the item that appears the most times in an array
本文介绍了获取数组中出现次数最多的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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屋!
查看全文