我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
仅ES5(即,它需要一个filter() polyfill用于IE8及以下):
var arrayToFilter = [ 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ];
arrayToFilter.
sort().
filter( function(me,i,arr){
return (i===0) || ( me !== arr[i-1] );
});
其他回答
最快的解决方法是用一面旗子
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(值))
我刚刚想出了一个简单的方法来实现这一点,使用数组过滤器
Var list = [9,9,111, 2,3,4,4,5,7]; //筛选1:找到所有重复的元素 Var duplicate = list.filter(函数(值,索引,self) { == self.lastIndexOf(value) && self.indexOf(value) === index; }); console.log(副本);
这也可以使用Set()来解决。
Set中的一个值只能出现一次;在Set的收藏中是独一无二的。
Array.prototype.hasDuplicates = function () {
if (arr.length !== (new Set(arr).size)) {
return true;
}
return false;
}
更多关于集合的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
注意:IE中不完全支持集合。
基于@ blumoon但更短,返回所有副本一次!
function checkDuplicateKeys(arr) {
const counts = {}
return arr.filter((item) => {
counts[item] = counts[item] || 1
if (counts[item]++ === 2) return true
})
}
// [1,2,2,2,2,2,2] => [1,2]
// ['dog', 'dog', 'cat'] => ['dog']
这是我能想到的最简单的解决办法:
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)
希望这能有所帮助。