除了常規的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]