我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
这是我用map实现的。它应该运行在O(n)时间,应该有点容易喘气。
var first_array = [1, 1, 2, 3, 4, 4, 5, 6); var find_dup=new Map; For (first_array的const迭代器){ //如果现值++ 如果(find_dup.has (iterator)) { find_dup.set(迭代器,find_dup.get(迭代器)+ 1); 其他}{ //否则添加 find_dup.set(迭代器,1); } } console.log (find_dup.get (2));
然后你可以find_dup.get(key)来查找它是否有重复(它应该给> 1)。
其他回答
这也可以使用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中不完全支持集合。
已经有很多答案了,但不幸的是,有些太长了,有些太短了,但对我来说太神秘了,而另一些则超出了我的知识范围……不过,我真的很喜欢我提出的这个解决方案。希望它仍然对一些人有帮助!
尽管最初的帖子说他/她实际上不需要重复的索引,也不需要重复多少次,但我认为仍然需要清楚地计算它们。
带有注释的代码。
function findDuplicates(array, count = {}) {
// with count declared in the parameter, initialized as an empty object,
// it can store the counts of all elements in array
// using the forEach loop to iterate through the input array,
// also using the conditional ternary operators
// (works just like a normal if-else statement, but just a bit cleaner)
// we can store all occurrences of each element from array in count
array.forEach(el => count[el] ? count[el]++ : count[el] = 1)
// using Object.keys, we get an array of all keys from count (all numbers)
// (sorted as well, though of no specific importance here)
// using filter to find all elements with a count (value) > 1 (duplicates!)
return Object.keys(count).filter(key => count[key] > 1);
}
只有代码(带有测试用例)。
函数findduplicate(数组,count = {}) { 数组中。forEach(el => count[el] ?Count [el]++: Count [el] = 1); 返回种(计数)。Filter (key => count[key] > 1); } 让arr1 = [9,9,111, 2,3,4,4,5,7]; 让arr2 = [1,6,7,3,6,8,1,3,4,5,1,7,2,6]; console.log (findDuplicates (arr1));// => ['4', '9'] console.log (findDuplicates (arr2));// => ['1', '3', '6', '7']
这应该是在数组中查找重复值的最短和最简单的方法之一。
Var arr = [1,2,3,4,5,6,7,8,1,2,3,4,5,3,4]; Var数据= arr.filter(函数(项目,索引,arr){ 返回arr.indexOf(item) != arr.lastIndexOf(item) && arr.indexOf(item) == index; }) console.log(数据);
const a = ['a', 'b', 'b']
function findDuplicates(a) {
return Object.keys(_.pickBy(_.countBy(a), x => x > 1))
}
https://runkit.com/nitzanav/62659f09bd2d5f0008ef46d4
我刚刚想出了一个简单的方法来实现这一点,使用数组过滤器
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(副本);