我需要检查 JavaScript 数组以查看是否存在重复值。做到这一点最简单的方法是什么?我只需要找到重复的值是什么 - 我实际上不需要它们的索引或它们重复了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有一种更简单的方法。
类似问题:
- 获取 JavaScript 数组中的所有唯一值(删除重复项) https://stackoverflow.com/questions/1960473
You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):
const findDuplicates = (arr) => {
let sorted_arr = arr.slice().sort(); // You can define the comparing function here.
// JS by default uses a crappy string compare.
// (we use slice to clone the array so the
// original array won't be modified)
let results = [];
for (let i = 0; i < sorted_arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
return results;
}
let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);
以防万一,如果您要作为重复项的函数返回。这是针对类似类型的案例。
参考:https://stackoverflow.com/a/57532964/8119511 https://stackoverflow.com/a/57532964/8119511
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)