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

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

类似的问题:

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


当前回答

这是一个方法,以避免重复到javascript数组…它支持字符串和数字…

 var unique = function(origArr) {
    var newArray = [],
        origLen = origArr.length,
        found,
        x = 0; y = 0;

    for ( x = 0; x < origLen; x++ ) {
        found = undefined;
        for ( y = 0; y < newArray.length; y++ ) {
            if ( origArr[x] === newArray[y] ) found = true;
        }
        if ( !found) newArray.push( origArr[x] );    
    }
   return newArray;
}

检查这个小提琴..

其他回答

我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。

这是一个有趣而简单的任务,有许多难以阅读的答案……

打印稿

function getDuplicatedItems<T>(someArray: T[]): T[] {
    // create a set to iterate through (we only need to check each value once)
    const itemSet = new Set<T>(someArray);

    // from that Set, we check if any of the items are duplicated in someArray
    const duplicatedItems = [...itemSet].filter(
        (item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
    );

    return duplicatedItems;
}

JavaScript

function getDuplicatedItems(someArray) {
    // check for misuse if desired
    // if (!Array.isArray(someArray)) {
    //     throw new TypeError(`getDuplicatedItems requires an Array type, received ${typeof someArray} type.`);
    // }
    const itemSet = new Set(someArray);
    const duplicatedItems = [...itemSet].filter(
        (item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
    );
    return duplicatedItems;
}

下面是使用sort()和JSON.stringify()实现的一个

https://gist.github.com/korczis/7598657

function removeDuplicates(vals) {
    var res = [];
    var tmp = vals.sort();

    for (var i = 0; i < tmp.length; i++) {
        res.push(tmp[i]);
                    while (JSON.stringify(tmp[i]) == JSON.stringify(tmp[i + 1])) {
            i++;
        }
    }

    return res;
}
console.log(removeDuplicates([1,2,3,4,5,4,3,3,2,1,]));

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

修改@RaphaelMontanaro的解决方案,借鉴@Nosredna的博客,如果你只想从数组中识别重复的元素,下面是你可以做的事情。

function identifyDuplicatesFromArray(arr) {
        var i;
        var len = arr.length;
        var obj = {};
        var duplicates = [];

        for (i = 0; i < len; i++) {

            if (!obj[arr[i]]) {

                obj[arr[i]] = {};

            }

            else
            {
                duplicates.push(arr[i]);
            }

        }
        return duplicates;
    }

感谢你优雅的解决方案,@Nosredna!

还有一种方法是使用下划线。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;
}, []);