找到阵列的模式?使用Javascript [英] Finding the mode's of an array? Javascript
本文介绍了找到阵列的模式?使用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,我只想出了如何从数组中获得一种模式..
但是如果它们出现相同的次数,我想获得2,3或更多。
这是代码:
Okay, I've only figured out how to get one mode out of the array.. But I want to get 2, 3 or more if they occur the same amount of times. This is the code:
var frequency = {}; // array of frequency.
var maxFreq = 0; // holds the max frequency.
for (var i in array) {
frequency[array[i]] = (frequency[array[i]] || 0) + 1; // increment frequency.
if (frequency[array[i]] > maxFreq) { // is this frequency > max so far ?
maxFreq = frequency[array[i]]; // update max.
mode = array[i]; // update result.
}
}
所以现在,如果我有一个 array = [3,8,3,6,1,2,9];
我得到 mode = 3;
So right now, if I've got a array = [3, 8, 3, 6, 1, 2, 9];
I get mode = 3;
但我正在寻找的是if array = [3,6,1,9,2,3,6, 6,3,1,-8,7];
我想得到 mode = 3,6;
But what I'm looking for is if array = [3, 6, 1, 9, 2, 3, 6, 6, 3, 1, -8, 7];
I want to get the mode = 3, 6;
推荐答案
问题没有说明如何获取模式,但如果我们想要它们在数组中,我们可以像这样更改代码:
The question doesn't state how to get the modes, but if we want them in an array, we could change the code like this:
function getModes(array) {
var frequency = {}; // array of frequency.
var maxFreq = 0; // holds the max frequency.
var modes = [];
for (var i in array) {
frequency[array[i]] = (frequency[array[i]] || 0) + 1; // increment frequency.
if (frequency[array[i]] > maxFreq) { // is this frequency > max so far ?
maxFreq = frequency[array[i]]; // update max.
}
}
for (var k in frequency) {
if (frequency[k] == maxFreq) {
modes.push(k);
}
}
return modes;
}
alert(getModes([3, 6, 1, 9, 2, 3, 6, 6, 3, 1, -8, 7]));
这篇关于找到阵列的模式?使用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文