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

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

类似的问题:

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


当前回答

这是我的建议(ES6):

let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]

// b is now [1, 2, 4]

其他回答

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

修改@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!

如果你想消除重复,试试这个好方法:

函数eliminateduplicate (arr) { var我, Len = arrr .length, Out = [], Obj = {}; For (i = 0;I < len;我+ +){ Obj [arr[i]] = 0; } 对于(i in obj) { out.push(我); } 返回; } console.log (eliminateDuplicates([1、6、7、3、6、8、1,3,4,5,1、7、2、6]))

来源: http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/

function GetDuplicates(arr) {
    var i = 0, m = [];
    return arr.filter(function (n) {
        return !m[n] * ~arr.indexOf(n, m[n] = ++i);
    });
}

最快的解决方法是用一面旗子

Var值= [4,2,3,1,4] / /解决方案 const checkDuplicate = list => { var hasDuplicate = false; list.sort()。排序((a, b) => { if (a == b) hasDuplicate = true }) 返回hasDuplicate } console.log (checkDuplicate(值))