简体   繁体   English

使用JavaScript查找数组中最大的重复值

[英]Find highest amount of repeating value in an array using JavaScript

I have an array with repeating values: 我有一个重复值的数组:

[0, 1, 6, 0, 1, 0]

What is an efficient way to return the highest amount that a specific value repeats? 返回特定值重复的最高金额的有效方法是什么?

In the example array I would want the script to return 3 because the number 0 repeats the most often and it repeats 3 times. 在示例数组中,我希望脚本返回3,因为数字0重复最多,并且重复3次。 I'm already using jQuery and Underscore. 我已经在使用jQuery和Underscore。

If you use lodash ... 如果您使用lodash ...

_.max(_.countBy(a,_.identity))

More about lodash: http://lodash.com/ 有关lodash的更多信息: http ://lodash.com/

This is similar to the basic approach, but utilizes underscore's reduce and max functions. 这类似于基本方法,但是利用了下划线的reducemax函数。 If you had a really really really large array, I hope it's clear how you could parallelize this with a map phase before the reduce. 如果您有一个非常大的数组,那么我希望您可以清楚地知道如何在缩小之前将其与map阶段并行化。

var arr = [1,0,2,3,4,0,3,0];
var counts = _.reduce(arr, function(counts, val) {
    if (counts[val]) {
        counts[val]++;
    } else {
        counts[val] = 1;
    }
    return counts;
}, {});
return _.max(counts);

Yay, this is like a google interview question lol. 是的,这就像一个Google面试问题。 I would recommend looping through your array once and maintaining an associative array of each element as you encounter it in the while incrementing a counter. 我建议循环遍历您的数组一次,并在递增计数器的同时维护每个元素的关联数组。

For example: 例如:

http://jsfiddle.net/btKjX/ http://jsfiddle.net/btKjX/

var a = [0, 0 , 2, 2, 3, 3, 3, 3];
var counts = {};

for(var i = 0, il = a.length; i < il; i++){
    var num = a[i];

    if(typeof counts[num] === 'undefined'){
        counts[num] = 0;
    }

    counts[num]++;
}

var max = -1;

for(var c in counts){
    if(counts[c] > max){
        max = counts[c];
    }
}

console.log(max);

a hacky way might be to sort it, split it on every value change and then look at the length of each string, but let's try something more reasonable: 一种怪异的方法可能是将其排序,在每次值更改时将其拆分,然后查看每个字符串的长度,但让我们尝试更合理的方法:

var nums = [0, 1, 6, 0, 1, 0]
var occurence = {}
$.each(nums, function(a, num_id) {
  if (occurence[num_id] != null) {
    occurence[num_id]++;
  } else {
    occurence[num_id] = 1;
  }
});

occurence would then have the number of occurences of every value in nums, with the number itself being the key. 然后,encenence将具有每个值的出现次数(以num为单位),而数字本身就是键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM