如何找到最重复的"值"在javascript数组?

时间:2018-04-03 05:23:41

标签: javascript arrays sorting

我的问题实际上类似于:Extracting the most duplicate value from an array in JavaScript (with jQuery)

我找到了这个,但它总是只返回一个值为200。



var arr = [100,100,200,200,200,300,300,300,400,400,400];
    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];
      }

    }
    console.log(res + " occurs " + counts[res] + " times");




请帮我回报价值而不只是一个......

结果应该是这样的: 200,300,400 。 请帮忙谢谢你!

5 个答案:

答案 0 :(得分:5)

您必须迭代计数才能找到最大发生结果。

var arr = [100,100,200,200,200,300,300,300,400,400,400];
    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];
      }

    }
    var results = [];
    for (var k in counts){
      if (counts[k] == max){
        //console.log(k + " occurs " + counts[k] + " times");
        results.push(k);
      }
    }
    console.log(results);

答案 1 :(得分:1)

使用for..in迭代数组并不是一个好主意。查看this链接以获取更多信息。

希望下面的代码段有用



var arr = [100, 100, 200, 200, 200, 300, 300, 300, 400, 400, 400];
//Use a reduce fuction to create an object where 100,200,300 
// will be keys and its value will the number of times it has 
//repeated
var m = arr.reduce(function(i, v) {
  if (i[v] === undefined) {
    i[v] = 1
  } else {
    i[v] = i[v] + 1;
  }
  return i;
}, {});
// Now get the maximum value from that object,
//getMaxRepeated will be 3 in this case

var getMaxRepeated = Math.max(...Object.values(m));
//An array to hold elements which are repeated 'getMaxRepeated' times
var duplicateItems = [];

// now iterate that object and push the keys which are repeated
//getMaxRepeated times
for (var keys in m) {
  if (m[keys] === getMaxRepeated) {
    duplicateItems.push(keys)
  }
}
console.log(duplicateItems)




答案 2 :(得分:1)

以下是假设arr中的所有项目都是数字的技巧:



//added some numbers assuming numbers are not sorted
var arr = [300,400,200,100,100,200,200,200,300,300,300,400,400,400];

var obj = arr.reduce(//reduce arr to object of: {"100":2,"200":4,"300":4,"400":4}
  (o,key)=>{//key is 100,200, ... o is {"100":numberOfOccurrences,"200":numberOf...}
    o[key] = (o[key])?o[key]+1:1;
    return o;
  },
  {}
);
// obj is now: {"100":2,"200":4,"300":4,"400":4}
//create an array of [{key:100,occurs:2},{key:200,occurs:4}...
var sorted = Object.keys(obj).map(
  key=>({key:parseInt(key),occurs:obj[key]})
)//sort the [{key:100,occurs:2},... by highest occurrences then lowest key
.sort(
  (a,b)=>
    (b.occurs-a.occurs===0)
      ? a.key - b.key
      : b.occurs - a.occurs
);
console.log(
  sorted.filter(//only the highest occurrences
    item=>item.occurs===sorted[0].occurs
  ).map(//only the number; not the occurrences
    item=>item.key
  )
);




答案 3 :(得分:0)

创建一个迭代arry的Object,其中包含大多数重复值的索引,如下面的

var arr = [100,100,200,200,200,300,300,300,400,400,400];
valObj = {}, max_length = 0, rep_arr = [];

arr.forEach(function(el,i){
   if(valObj.hasOwnProperty(el)){
       valObj[el] += 1;
       max_length = (valObj[el] > max_length) ? valObj[el] : max_length
   }
   else{
       valObj[el] = 1;
   }
});

Object.keys(valObj).forEach(function(val){
    (valObj[val] >= max_length) && (rep_arr.push(val))
});
console.log(rep_arr);

使用key作为数组值创建对象并将值作为该值的数组索引创建后,可以播放/解析该值。希望这会有所帮助。

答案 4 :(得分:0)

请尝试以下==>

function getDuplicate( arr ){
    let obj = {}, dup = [];
    for(let i = 0, l = arr.length; i < l; i++){
        let val = arr[i];
        if( obj[val] /**[hasOwnProperty]*/ ) {
            /**[is exists]*/
            if(dup.find(a => a == val) ) continue;
            /**[put Unique One]*/
            dup.push(val);
            continue;
        };
        /**[hold for further use]*/
        obj[val] = true;
    }
    return dup;
};

使用==&gt;

getDuplicate([100,100,200,200,200,300,300,300,400,400,400]);