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

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

类似的问题:

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


当前回答

Prototype库有一个uniq函数,它返回不包含dupes的数组。但这只是工作的一半。

其他回答

var arr = ['a','b','c','a'];

arr.filter( (item , index ) => {  
console.log(item , index , arr.indexOf(item) , arr.indexOf( item ) == index);
return index == arr.indexOf(item)
 } );

/* 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;
}

这将从数组中返回副本作为副本数组。

Const duplicate = function(arr) { //让我们试着两人一组。也许会有用 let dups = new Set(), R = [] arr.sort () 加勒比海盗。Reduce ((pv, cv) => { If (pv === cv) { dups.add (pv) } 返回的简历 }) For (let m of dpps .values()) { r.push (m) } 返回r } console.log(副本([1、3、5、6、7、4、4、5、1、4、6、3、8、9日5 0]))

ES6语法的简单代码(返回重复的排序数组):

let duplicates = a => {d=[]; a.sort((a,b) => a-b).reduce((a,b)=>{a==b&&!d.includes(a)&&d.push(a); return b}); return d};

使用方法:

duplicates([1,2,3,10,10,2,3,3,10]);
var a= [1, 2,2,3,3,4,4,4];
var m=[];
var n = [];
a.forEach(function(e) {
  if(m.indexOf(e)=== -1) {
    m.push(e);
}else if(n.indexOf(e)=== -1){
    n.push(e);
}

});