我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
我更喜欢函数法。
function removeDuplicates(links) {
return _.reduce(links, function(list, elem) {
if (list.indexOf(elem) == -1) {
list.push(elem);
}
return list;
}, []);
}
它使用下划线,但Array也有一个reduce函数
其他回答
var arr = ['a','b','c','a'];
arr.filter( (item , index ) => {
console.log(item , index , arr.indexOf(item) , arr.indexOf( item ) == index);
return index == arr.indexOf(item)
} );
这是一种单循环方法,使用哈希表来计数元素,如果计数为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(副本);
[1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 50, 8, 5, 22, 1, 2, 511, 12, 50, 22].reduce(function (total, currentValue, currentIndex, arr) {
if (total.indexOf(currentValue) === -1 && arr.indexOf(currentValue) !== currentIndex)
total.push(currentValue);
return total;
}, [])
遵循逻辑会更容易、更快
// @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()方法更高效、更快。
这是我能想到的最简单的解决办法:
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)
希望这能有所帮助。