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

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

类似的问题:

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


当前回答

var a = [324,3,32,5,52,2100,1,20,2,3,3,2,2,2,1,1,1].sort();
a.filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});

或者当添加到原型时。阵列链

//copy and paste: without error handling
Array.prototype.unique = 
   function(){return this.sort().filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});}

请看这里:https://gist.github.com/1305056

其他回答

下面的函数(前面提到的eliminateduplates函数的变体)似乎可以做到这一点,它为输入["test", "test2", "test2", 1,1,2,3,4,5,6,7,7,10,22,43,1,5,5,8]返回test2,1,7,7,8]。

请注意,这个问题在JavaScript中比在大多数其他语言中更奇怪,因为JavaScript数组几乎可以容纳任何东西。注意,使用排序的解决方案可能需要提供适当的排序函数——我还没有尝试过这种方法。

这个特殊的实现(至少)适用于字符串和数字。

function findDuplicates(arr) {
    var i,
        len=arr.length,
        out=[],
        obj={};

    for (i=0;i<len;i++) {
        if (obj[arr[i]] != null) {
            if (!obj[arr[i]]) {
                out.push(arr[i]);
                obj[arr[i]] = 1;
            }
        } else {
            obj[arr[i]] = 0;            
        }
    }
    return out;
}

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

在这里,每个dupe只输出一次副本。

Var arr = [9,9,9,9,111, 2,3,4,4,5,7]; arr.sort (); Var结果= []; For (var I = 0;我< arr。长度- 1;我+ +){ 如果(arr[i + 1] == arr[i]) { results.push (arr[我]); } } results = Array.from(new Set(results)) console.log(结果);

最简单快捷的方法是使用Set对象:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const set = new Set(numbers);

const duplicates = numbers.filter(item => {
    if (set.has(item)) {
        set.delete(item);
        return false;
    } else {
        return true;
    }
});

// OR more concisely

const duplicates = numbers.filter(item => !set.delete(item));

console.log(duplicates);
// [ 2, 5 ]

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

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