从 JavaScript 中的数组中提取最多重复的值(使用 jQuery) [英] Extracting the most duplicate value from an array in JavaScript (with jQuery)

查看:66
本文介绍了从 JavaScript 中的数组中提取最多重复的值(使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆