除了常规的for循环方法数组去重,今天看es6 时,想总结一下es6数组去重:
数组去重:
1.使用es6中的扩展运算符(...)和Set
let a=[1,2,3,4,4,5,6,5,4]
a = [...new Set(a)] // [1,2,3,4,5,6]
注:new Set ()不会进行类型转化,5和'5'是两个不同的值,但是NaN与NaN相等
let arr = [...new Set([NaN,NaN])] // [NaN]
2.使用es6中的Array.from 和 Set 结合
function dedupe (Array) { return Array.from(new Set(Array)) }
let arr = dedupe([1,2,3,4,4,5,6,5,6])
数组合并去重:
let arr1 = [1,2,3,4,4] let arr2 = [3,4,5,6,7,6] let arr = [...new Set([...arr1, arr2])] //[1,2,3,4,5,6,7]