我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
遵循逻辑会更容易、更快
// @Param:data:Array that is the source
// @Return : Array that have the duplicate entries
findDuplicates(data: Array<any>): Array<any> {
return Array.from(new Set(data)).filter((value) => data.indexOf(value) !== data.lastIndexOf(value));
}
优点:
单行:-P 所有内置的数据结构有助于提高效率 快
逻辑描述:
转换为集以删除所有重复项 遍历设置的值 对于每个设置值,在源数组中检查条件"值的第一个索引不等于最后一个索引" == >则推断为重复否则为'唯一'
注意:map()和filter()方法更高效、更快。
其他回答
这是一种单循环方法,使用哈希表来计数元素,如果计数为2则过滤数组,因为它返回第一个找到的重复元素。
优势:
单回路 在闭包中使用对象进行计数
数组var =[5 0、2、1、2、3、3、4、4、8、6、7、9,4], duplicate = array。过滤器((h = > v = > (h [v] = (h [v] | | 0) + 1) = = = 2) ({})); console.log(副本);
这是我能想到的最简单的解决办法:
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)
希望这能有所帮助。
在一次采访中有人问我这个问题,我的回答是,
List<int> getDublicates(List<int> x)
{
List<int> result = new List<int>();
while (x.Count>0)
{
int d = x[0];
x.Remove(x[0]);
if (x.Contains(d))
result.Add(d);
}
return result;
}
它的性能很好
这是基于出现次数的更高级的函数。
function getMostDuplicated(arr, count) {
const result = [];
arr.forEach((item) => {
let i = 0;
arr.forEach((checkTo) => {
if (item === checkTo) {
i++;
if (i === count && result.indexOf(item) === -1) {
result.push(item);
}
}
});
});
return result;
}
arr = [1,1,1,2,5,67,3,2,3,2,3,1,2,3,4,1,4];
result = getMostDuplicated(arr, 5); // result is 1
result = getMostDuplicated(arr, 2); // result 1, 2, 3, 4
console.log(result);
我刚刚想出了一个简单的方法来实现这一点,使用数组过滤器
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(副本);