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

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

类似的问题:

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


当前回答

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

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

其他回答

仅ES5(即,它需要一个filter() polyfill用于IE8及以下):

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

我更喜欢函数法。

function removeDuplicates(links) {
    return _.reduce(links, function(list, elem) { 
        if (list.indexOf(elem) == -1) {
            list.push(elem);
        }   
        return list;
    }, []);
}

它使用下划线,但Array也有一个reduce函数

更新:简短的一行程序,以获得副本:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]

要获得没有重复项的数组,只需反转条件:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]

注意,这个答案的主要目标是简短。如果你需要一个大数组的性能,一个可能的解决方案是先排序你的数组(如果它是可排序的),然后执行以下操作来获得与上面相同的结果:

myHugeSortedArray.filter((e, i, a) => a[i-1] === e)

下面是一个1 000 000个整数数组的例子:

const myHugeIntArrayWithDuplicates =
  [...Array(1_000_000).keys()]
  // adding two 0 and four 9 duplicates
  .fill(0, 2, 4).fill(9, 10, 14)

console.time("time")
console.log(
  myHugeIntArrayWithDuplicates
  // a possible sorting method for integers
  .sort((a, b) => a > b ? 1 : -1)
  .filter((e, i, a) => a[i-1] === e)
)
console.timeEnd("time")

在我的AMD Ryzen 7 5700G开发机上输出:

[ 0, 0, 9, 9, 9, 9 ]
time: 22.738ms

正如在评论中指出的那样,短解决方案和性能解决方案都将返回一个具有多次相同副本的数组,如果它在原始数组中出现多次:

[1, 1, 1, 2, 2, 2, 2].filter((e, i, a) => a.indexOf(e) !== i) // [1, 1, 2, 2, 2]

如果需要唯一的副本,则函数为

function duplicates(arr) {
  return [...new Set(arr.filter((e, i, a) => a.indexOf(e) !== i))]
}

可以使用duplicate([1, 1, 1, 2, 2, 2, 2])返回[1,2]。


当你所需要的只是检查是否像这个问题中要求的那样没有重复时,你可以使用every()方法:

[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true

[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false

注意,every()在ie8及以下版本中不起作用。

以O(n)时间复杂度(不排序)求解上述问题。

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];

var obj={};

for(var i=0;i<arr.length;i++){
    if(!obj[arr[i]]){
        obj[arr[i]]=1;
    } else {
        obj[arr[i]]=obj[arr[i]]+1;
    }
}
var result=[]
for(var key in obj){
    if(obj[key]>1){
        result.push(Number(key)) // change this to result.push(key) to find duplicate strings in an array
    }
}

console.log(result)
const a = ['a', 'b', 'b']

function findDuplicates(a) {
    return Object.keys(_.pickBy(_.countBy(a), x => x > 1))
}

https://runkit.com/nitzanav/62659f09bd2d5f0008ef46d4