TK.*_*TK. 3 javascript arrays jquery
我有几个数组要处理.我需要从每个数组中提取最多的重复值.
从[3, 7, 7, 7],我需要找到价值7.每个数组大小为4.现在,我不必考虑何时最重复的值多于一个,例如[3, 7, 7, 7].所有值都是数字.
我环顾网络.我发现了几种使阵列成为的方法uniq().但我还没有找到获得重复值的方法.我正在使用jQuery,但原始JavaScript适用于此任务.
在效率方面并不完美,但是工作:
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).");
}
?
Run Code Online (Sandbox Code Playgroud)
这是一个仅使用 JavaScript 的更简单、更快的版本:
var arr = [3, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1];
var counts = {}, max = 0, res;
for (var v in arr) {
counts[arr[v]] = (counts[arr[v]] || 0) + 1;
if (counts[arr[v]] > max) {
max = counts[arr[v]];
res = arr[v];
}
}
alert(res + " occurs " + counts[res] + " times");
Run Code Online (Sandbox Code Playgroud)
请注意,这是一种更有效的方法,因为您只循环一次数据,如果您对非常大的数组进行排序,这将开始变得重要。