【问题标题】:How to find the most duplicate "values" in javascript array?如何在javascript数组中找到最重复的“值”?
【发布时间】:2018-04-03 05:23:41
【问题描述】:

我的问题其实类似于: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 . 请帮忙谢谢!

【问题讨论】:

  • 因此,您希望 all 值与最高重复计数(如果存在平局)相关联,是这样吗?
  • 是的先生请帮忙
  • 结果是这样的数组:[200,300,400]

标签: javascript arrays sorting


【解决方案1】:

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

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);

【讨论】:

  • 先生,您能否将结果传递到这样的数组中 [200,300,400]
  • @PauloDelaCruz 现在看看。这是你的要求吗?
【解决方案2】:

创建一个对象迭代包含大多数重复值的索引的数组,如下所示

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);

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

【讨论】:

  • 你不觉得它不必要的复杂吗?你让你的代码难以调试。
  • 我个人觉得调试不难,只是创建json对象,以数组值为key,以jsonkey值出现在数组中的次数,谁会觉得很难调试?正如我所看到的,除了创建对象之外,您的代码也遵循相同的逻辑,就是这样。无论如何感谢您的建议! :)
  • 您上次的编辑很好。现在它更容易理解了。
【解决方案3】:

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

希望sn-p下面会有用

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)

【讨论】:

    【解决方案4】:

    假设 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
      )
    );

    【讨论】:

      【解决方案5】:

      尝试如下 ==>

      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;
      };
      

      使用 ==>

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

      【讨论】:

        【解决方案6】:

        尝试以下方法:

        var candles = [100,100,200,200,200,300,300,300,400,400,400];
        
        let tempArray = {}
        
        for (let index = 0; index <= (candles.length - 1); index++) {
        
            let valueToCompare = candles[index];
        
            if (tempArray[valueToCompare]) {
                tempArray[valueToCompare] = tempArray[valueToCompare] + 1;
            } else {
                tempArray[valueToCompare] = 1;
            }
        }
        
        let highestValue;
        Object.values(tempArray).forEach(item => {
            
        
            if (highestValue === undefined) highestValue = item;
        
            if (highestValue < item) highestValue = item;
        });
        
        console.log(highestValue);
        

        【讨论】:

          猜你喜欢
          • 2017-05-30
          • 1970-01-01
          • 1970-01-01
          • 2021-11-09
          • 2019-09-21
          • 1970-01-01
          • 1970-01-01
          • 2019-04-08
          • 2017-12-20
          相关资源
          最近更新 更多