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

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

类似的问题:

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


当前回答

简单的一行方式

Var arr = [9,1,2,4,3,4,9] console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //获取副本 console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //删除重复项

其他回答

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

下面是一个简单的小片段,用于查找唯一的和重复的值,无需排序和两个循环。

Var _unique =函数(arr) { Var h = [], t = []; 加勒比海盗。forEach(函数(n) { if (h.indexOf(n) == -1) h.push (n); 其他t.push (n); }); 返回[h, t]; } var =结果_unique([“测试”,1 4 2,34岁,6日,21日,3,4,“测试”、“王子”、“th”,34]); console.log("Has duplicate values: " + (result[1]. log)长度> 0))//你可以检查重复值的计数 Console.log (result[0]) //唯一值 Console.log (result[1]) //重复值

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 arr =[1、2、2、2 0,0,0,500,1,“,”“,”“) Const filtered = arr。filter((el, index) => arr.indexOf(el) !== index) // => filtered = [2,2,0,0, -1, 'a', 'a'] Const duplicate =[…]新的(过滤) console.log(副本) // => [2,0, -1, 'a']

就是这样。

注意:

It works with any numbers including 0, strings and negative numbers e.g. -1 - Related question: Get all unique values in a JavaScript array (remove duplicates) The original array arr is preserved (filter returns the new array instead of modifying the original) The filtered array contains all duplicates; it can also contain more than 1 same value (e.g. our filtered array here is [ 2, 2, 0, 0, -1, 'a', 'a' ]) If you want to get only values that are duplicated (you don't want to have multiple duplicates with the same value) you can use [...new Set(filtered)] (ES6 has an object Set which can store only unique values)

希望这能有所帮助。