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

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

类似的问题:

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


当前回答

这个答案可能也有帮助,它利用js的reduce操作符/方法从数组中删除重复项。

Const result =[1,2,2,3,3,3,3]。Reduce ((x, y) => x.includes(y) ?X:[…]X, y], []); console.log(结果);

其他回答

在这篇文章是有用的重复检查,如果你正在使用Jquery。

如何使用jquery在数组中找到重复项

var unique_values = {}; var list_of_values = []; $('input[name$="recordset"]').     each(function(item) {          if ( ! unique_values[item.value] ) {             unique_values[item.value] = true;             list_of_values.push(item.value);         } else {             // We have duplicate values!         }     });

/* Array对象的indexOf方法用于比较数组项。 IE是唯一一个原生不支持它的主流浏览器,但它很容易实现: * /

Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    i= i || 0;
    var L= this.length;
    while(i<L){
        if(this[i]=== what) return i;
        ++i;
    }
    return -1;
}

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1 && dups.indexOf(itm)== -1){
            dups[dups.length]= itm;
        }
    }
    return dups;
}

var a1= [1, 22, 3, 2, 2, 3, 3, 4, 1, 22, 7, 8, 9];

警报(getarrayduplicates (a1));

对于非常大的数组,可以更快地从数组中删除找到的重复项,这样就不会再次查看它们:

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1){
            dups[dups.length]= itm;
            while(A.indexOf(itm)!= -1){
                A.splice(A.indexOf(itm), 1);
            }
        }
    }
    return dups;
}

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

[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及以下版本中不起作用。

这应该是在数组中查找重复值的最短和最简单的方法之一。

Var arr = [1,2,3,4,5,6,7,8,1,2,3,4,5,3,4]; Var数据= arr.filter(函数(项目,索引,arr){ 返回arr.indexOf(item) != arr.lastIndexOf(item) && arr.indexOf(item) == index; }) console.log(数据);

还有一种方法是使用下划线。Numbers是源数组,dupes可能有重复的值。

var itemcounts = _.countBy(numbers, function (n) { return n; });
var dupes = _.reduce(itemcounts, function (memo, item, idx) {
    if (item > 1)
        memo.push(idx);
    return memo;
}, []);