我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。

我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。

类似的问题:

获取JavaScript数组中所有唯一的值(删除重复值)


当前回答

http://jsfiddle.net/vol7ron/gfJ28/

var arr  = ['hello','goodbye','foo','hello','foo','bar',1,2,3,4,5,6,7,8,9,0,1,2,3];
var hash = [];

// build hash
for (var n=arr.length; n--; ){
   if (typeof hash[arr[n]] === 'undefined') hash[arr[n]] = [];
   hash[arr[n]].push(n);
}


// work with compiled hash (not necessary)
var duplicates = [];
for (var key in hash){
    if (hash.hasOwnProperty(key) && hash[key].length > 1){
        duplicates.push(key);
    }
}    
alert(duplicates);

The result will be the hash array, which will contain both a unique set of values and the position of those values. So if there are 2 or more positions, we can determine that the value has a duplicate. Thus, every place hash[<value>].length > 1, signifies a duplicate. hash['hello'] will return [0,3] because 'hello' was found in node 0 and 3 in arr[]. Note: the length of [0,3] is what's used to determine if it was a duplicate. Using for(var key in hash){ if (hash.hasOwnProperty(key)){ alert(key); } } will alert each unique value.

其他回答

简单的一行方式

Var arr = [9,1,2,4,3,4,9] console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //获取副本 console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //删除重复项

你可以使用下面的代码来获取给定数组中的重复元素:

let name = ['satya', 'amit', 'aditya', 'abhay', 'satya', 'amit'];
let dup = [];
let uniq = [];
name.forEach((item, index) => {
  if(!uniq.includes(item)) {
    uniq[index] = item;
  }
  if (name.indexOf(item, index + 1) != -1) {
    dup[index] = item;
  }
})

打印重复值

var arr = [1,2,3,4,13,2,3,4,3,4]; // non_unique Printing function nonUnique(arr){ var result = []; for(var i =0;i<arr.length;i++){ if(arr.indexOf(arr[i],i+1) > -1){ result.push(arr[i]); } } console.log(result); }nonUnique(arr); // unique Printing function uniqueDuplicateVal(arr){ var result = []; for(var i =0;i<arr.length;i++){ if(arr.indexOf(arr[i],i+1) > -1){ if(result.indexOf(arr[i]) === -1]){ result.push(arr[i]); } } } } uniqueDuplicateVal(arr)

排名较高的答案有一些固有的问题,包括使用遗留的javascript,不正确的排序或只支持2个重复的项目。

这里有一个解决这些问题的现代解决方案:

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']

你也可以使用npm包array-non-uniq。

这是我的建议(ES6):

let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]

// b is now [1, 2, 4]