从一个数组在JavaScript中提取最重复的值(用jQuery) [英] Extracting the most duplicate value from an array in JavaScript (with jQuery)
问题描述
我有几个阵列来处理。我需要提取每个阵列最重复的值。
I have several array to deal with. I need to extract the most duplicate value from each array.
从 [3,7,7,7]
,我需要找到值 7
。每个数组的大小为4。现在,我没有去想的时候最重复的值不止一个,如 [3,7,7,7]
。所有的值是一个数。
From [3, 7, 7, 7]
, I need to find the value 7
. Each array size is 4. For now, I don't have to think about when the most duplicate values are more than one such as [3, 7, 7, 7]
. All the values are a number.
我看了看各地的网络。我发现了几个办法,使阵列成为的uniq()
。但我还没有找到一种方式来获得重复的值。我使用jQuery,但原料JavaScript是罚款这项任务。
I looked around the web. I found several ways to make an array to become uniq()
. But I haven't found a way to get the duplicate value. I am using jQuery, but raw JavaScript is fine for this task.
推荐答案
未在效率方面完美的,但做这项工作:
Not perfect in terms of efficiency, but does the job:
var nums = [3, 7, 7, 7];
var freqs = {};
var max_index;
var max_value = -1/0; // Negative infinity.
$.each(nums, function(i, v) {
if (freqs[v] != undefined) {
freqs[v]++;
} else {
freqs[v] = 1;
}
});
$.each(freqs, function(num, freq) {
if (freq > max_value) {
max_value = freq;
max_index = num;
}
});
if (max_index != undefined) {
alert("Most common element is " + max_index + " with " + max_value + " repetition(s).");
}
这篇关于从一个数组在JavaScript中提取最重复的值(用jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!