查找数组中出现频率最高的项(不仅仅是字符串) [英] Find the most frequent item of an array (not just strings)
本文介绍了查找数组中出现频率最高的项(不仅仅是字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以指导我完成这个练习吗?编写一个 JavaScript 程序来查找数组中最频繁的项.
Can someone walk me through this exercise? Write a JavaScript program to find the most frequent item of an array.
var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var mf = 1;
var m = 0;
var item;
for (var i = 0; i < arr1.length; i++) {
for (var j = i; j < arr1.length; j++) {
if (arr1[i] == arr1[j]) m++;
if (mf < m) {
mf = m;
item = arr1[i];
}
}
m = 0;
}
alert(item + " ( " + mf + " times ) ");
我一直在查看有关 stackoverflow 的一些类似问题,只是找不到我想要的答案.
I've been checking out some similar questions on stackoverflow, just can't find the answers that I want.
我的问题是:
我不明白为什么需要有两个 for 循环.
I don't understand why there needs to have two for loops.
为什么需要 mf
和 m
.看起来有点混乱.
Why the need for mf
and m
. Seems a bit confusing.
有没有其他解决方法?
推荐答案
我真的不认为在这个解决方案中需要 2 个循环.你可以看看这个原型代码,它使用了一个叫做 map 的简单数据结构:
I really do not think there is a need for 2 loops in this solution. You can look at this prototyping code which uses a simple data structure called map:
var arr=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
var map = {};
var mostFrequentElement = arr[0];
function findMostFrequent(){
for(var i = 0; i<arr.length; i++){
if(!map[arr[i]]){
map[arr[i]]=1;
}else{
++map[arr[i]];
if(map[arr[i]]>map[mostFrequentElement]){
mostFrequentElement = arr[i];
}
}
}
alert(mostFrequentElement);
}
这篇关于查找数组中出现频率最高的项(不仅仅是字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文