ES6 Set 常用

Set 對象作用

數組去重,注意4 ‘4’ 不同

let arr = [1, 2, 3, 4, 4, '4', '4'];
let mySet = new Set(arr);
[...mySet]; // [1, 2, 3, 4, '4']

 

並集

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]); 
let union = new Set([...a, ...b]); // {1, 2, 3, 4}
[...union] // [1,2,3,4]

 

交集

let a = new Set([1, 2, 3]); 
let b = new Set([4, 3, 2]); 
let intersect = new Set([...a].filter(x => b.has(x))); // {2, 3}
[...intersect] // [2,3]

 

差集

let a = new Set([1, 2, 3]); 
let b = new Set([4, 3, 2]); 
let difference = new Set([...a].filter(x => !b.has(x))); // {1}
[...difference] // [1]

 

 

 

 

.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章