【问题标题】:Get distinct duplicates from array从数组中获取不同的重复项
【发布时间】:2019-10-30 04:12:54
【问题描述】:

我有一个数组[1,1,1,1,2,3,4,5,5,6,7,8,8,8]

如何获得不同重复的数组[1,5,8] - 结果中的每个重复仅一次,无论它在原始数组中出现多少次

我的代码:

var types = availControls.map(item => item.type);
var sorted_types = types.slice().sort();

availControlTypes = [];
for (var i = 0; i < sorted_types.length - 1, i++) {
   if (sorted_types[i + 1] == sorted_types[i])
   availControlTypes.push(sorted_types[i]);
}

这让我得到了重复,但不是唯一的。

【问题讨论】:

  • 好的,你的代码在哪里,你需要帮助的复杂部分是什么?
  • @Dalorzo 添加。
  • .map 和箭头函数是 ES6 特性...你确定你使用的是 pre-ES5 代码吗?
  • 不确定,我尝试使用...Set,但它没有用...但我把它排除在外
  • 这个问题的公认答案就是你需要的stackoverflow.com/questions/49215358/…

标签: javascript arrays


【解决方案1】:

这样就可以了

var input = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];

let filterDuplicates = arr => [...new Set(arr.filter((item, index) => arr.indexOf(item) != index))]


console.log(filterDuplicates(input)) 

【讨论】:

    【解决方案2】:

    您需要一个 for 循环,其对象将保存该数字在数组中出现的次数。当计数已经为 1 时,我们可以将该项添加到结果中。我们应该继续增加计数器,所以我们不会添加多个相同数字的重复项(尽管我们可以在 2 处停止)。

    function fn(arr) {
      var counts = {};
      var result = [];
      var n;
      
      for(var i = 0; i < arr.length; i++) {
        n = arr[i]; // get the current number
        
        if(counts[n] === 1) result.push(n); // if counts is exactly 1, we should add the number to results
        
        counts[n] = (counts[n] || 0) +1; // increment the counter
      }
      
      return result;
    }
    
    var arr = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];
    
    var result = fn(arr);
    
    console.log(result)

    【讨论】:

      【解决方案3】:
      const dupes = arr =>
        Array.from(
          arr.reduce((acc, item) => {
            acc.set(item, (acc.get(item) || 0) + 1);
            return acc;
          }, new Map())
        )
          .filter(x => x[1] > 1)
          .map(x => x[0]);
      
      const arr = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];
      
      console.log(dupes(arr));
      
      // [ 1, 5, 8 ]
      

      【讨论】:

        【解决方案4】:

        ES6 1 衬里。 这与我们查找唯一值的方式非常相似,只是我们不是过滤第一次出现,而是过滤第二次出现。

        let nthOccurrences = (a, n = 1) => a.filter((v, i) => a.filter((vv, ii) => vv === v && ii <= i).length === n);
        
        let x = [1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 8];
        
        let uniques = nthOccurrences(x, 1);
        let uniqueDuplicates = nthOccurrences(x, 2);
        let uniqueTriplets = nthOccurrences(x, 3); // unique values with 3 or more occurrences
        
        console.log(JSON.stringify(uniques));
        console.log(JSON.stringify(uniqueDuplicates));
        console.log(JSON.stringify(uniqueTriplets));

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-20
          • 1970-01-01
          • 2014-07-30
          相关资源
          最近更新 更多