获取数组中的所有非唯一值(即:重复/多次出现)

本文翻译自:Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

I need to check a JavaScript array to see if there are any duplicate values. 我需要检查一个JavaScript数组,看看是否有重复的值。 What's the easiest way to do this? 最简单的方法是什么? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated. 我只需要查找重复的值是什么-我实际上不需要它们的索引或它们被重复多少次。

I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way. 我知道我可以遍历数组并检查所有其他值是否匹配,但是似乎应该有一种更简单的方法。

Similar question: 类似的问题:


#1楼

参考:https://stackoom.com/question/3Wiz/获取数组中的所有非唯一值-即-重复-多次出现


#2楼

ES5 only (ie, it needs a filter() polyfill for IE8 and below): 仅适用于ES5(即,它需要针对IE8及更低版本的filter()polyfill):

var arrayToFilter = [ 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ];

arrayToFilter.
    sort().
    filter( function(me,i,arr){
       return (i===0) || ( me !== arr[i-1] );
    });

#3楼

using underscore.js 使用underscore.js

function hasDuplicate(arr){
    return (arr.length != _.uniq(arr).length);
}

#4楼

var input = ['a', 'b', 'a', 'c', 'c'],
    duplicates = [],
    i, j;
for (i = 0, j = input.length; i < j; i++) {
  if (duplicates.indexOf(input[i]) === -1 && input.indexOf(input[i], i+1) !== -1) {
    duplicates.push(input[i]);
  }
}

console.log(duplicates);

#5楼

Here is a very light and easy way: 这是一个非常简便的方法:

var codes = dc_1.split(',');
var i = codes.length;
while (i--) {
  if (codes.indexOf(codes[i]) != i) {
    codes.splice(i,1);
  }
}

#6楼

I think the below is the easiest and fastest O(n) way to accomplish exactly what you asked: 我认为以下是完成您所要求的最简单,最快的O(n)方法:

function getDuplicates( arr ) {
  var i, value;
  var all = {};
  var duplicates = [];

  for( i=0; i<arr.length; i++ ) {
    value = arr[i];
    if( all[value] ) {
      duplicates.push( value );
      all[value] = false;
    } else if( typeof all[value] == "undefined" ) {
      all[value] = true;
    }
  }

  return duplicates;
}

Or for ES5 or greater: 或对于ES5或更高版本:

function getDuplicates( arr ) {
  var all = {};
  return arr.reduce(function( duplicates, value ) {
    if( all[value] ) {
      duplicates.push(value);
      all[value] = false;
    } else if( typeof all[value] == "undefined" ) {
      all[value] = true;
    }
    return duplicates;
  }, []);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值