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

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

类似的问题:

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


当前回答

[1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 50, 8, 5, 22, 1, 2, 511, 12, 50, 22].reduce(function (total, currentValue, currentIndex, arr) {
    if (total.indexOf(currentValue) === -1 && arr.indexOf(currentValue) !== currentIndex) 
        total.push(currentValue);
    return total;
}, [])

其他回答

令人惊讶的是没有人发布这个解决方案。

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>
</title>
</head>
<body>
  <script>
       var list = [100,33,45,54,9,12,80,100];
       var newObj = {};
       var newArr = [];
        for(var i=0; i<list.length; i++){
          newObj[list[i]] = i;               
        }
        for(var j in newObj){
            newArr.push(j);  
        }
       console.log(newArr);
  </script>
</body>
</html>

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

函数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/

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

});

排名较高的答案有一些固有的问题,包括使用遗留的javascript,不正确的排序或只支持2个重复的项目。

这里有一个解决这些问题的现代解决方案:

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']

你也可以使用npm包array-non-uniq。

const a = ['a', 'b', 'b']

function findDuplicates(a) {
    return Object.keys(_.pickBy(_.countBy(a), x => x > 1))
}

https://runkit.com/nitzanav/62659f09bd2d5f0008ef46d4