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

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

类似的问题:

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


当前回答

最短的香草JS:

[1,1,2,2,2,3].filter((v,i,a) => a.indexOf(v) !== i) // [1, 2, 2]

其他回答

这是我在重复线程(!)中的回答:

在2014年写这篇文章时,所有的例子都是for-loops或jQuery。JavaScript有完美的工具:排序、映射和缩减。

找到重复的物品

var名称=[“迈克”,“马特”,“南希”,“亚当”,“珍妮”,“南希”,“卡尔”) Const uniq = names .map((name) => { 返回{ 数:1 名称:名称 }; }) .reduce((result, b) => { Result [b.name] = (Result [b.name] || 0) + b.count; 返回结果; }, {}); const duplicate = Object.keys(uniq).filter((a) => uniq[a] > 1); console.log(副本);// ['Nancy']

更多函数式语法:

@Dmytro-Laptin指出了一些可以删除的代码。这是相同代码的一个更紧凑的版本。使用一些ES6技巧和高阶函数:

常量名称=[“迈克”,“马特”,“南希”,“亚当”,“珍妮”,“南希”,“卡尔”); Const count = names => 的名字。Reduce ((result, value) =>({… [value]:(result[value] || 0) + 1 }, {});//不要忘记初始化累加器 Const duplicate = dict => Object.keys(dict).filter((a) => dict[a] > 1); console.log (count(名称));//{迈克:1,马特:1,南希:2,亚当:1,珍妮:1,卡尔:1} console.log(副本(count(名字)));// ['Nancy']

我们将使用Javascript ES6功能来做魔术!

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
const filtered = arr.filter((value, index) => {
 return arr.indexOf(value) >= index;
});

console.log(filtered);

https://jsfiddle.net/97Lxupnz/

//find duplicates: //sort, then reduce - concat values equal previous element, skip others //input var a = [1, 2, 3, 1, 2, 1, 2] //short version: var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, []) console.log(duplicates); //[1, 1, 2, 2] //readable version: var duplicates = a.sort().reduce((output, element, index, input) => { if ((index > 0) && (element === input[index - 1])) return output.concat(element) return output }, []) console.log(duplicates); //[1, 1, 2, 2]

这是我能想到的最简单的解决办法:

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)

希望这能有所帮助。

http://jsfiddle.net/vol7ron/gfJ28/

var arr  = ['hello','goodbye','foo','hello','foo','bar',1,2,3,4,5,6,7,8,9,0,1,2,3];
var hash = [];

// build hash
for (var n=arr.length; n--; ){
   if (typeof hash[arr[n]] === 'undefined') hash[arr[n]] = [];
   hash[arr[n]].push(n);
}


// work with compiled hash (not necessary)
var duplicates = [];
for (var key in hash){
    if (hash.hasOwnProperty(key) && hash[key].length > 1){
        duplicates.push(key);
    }
}    
alert(duplicates);

The result will be the hash array, which will contain both a unique set of values and the position of those values. So if there are 2 or more positions, we can determine that the value has a duplicate. Thus, every place hash[<value>].length > 1, signifies a duplicate. hash['hello'] will return [0,3] because 'hello' was found in node 0 and 3 in arr[]. Note: the length of [0,3] is what's used to determine if it was a duplicate. Using for(var key in hash){ if (hash.hasOwnProperty(key)){ alert(key); } } will alert each unique value.