Set 对象作用
2022年4月14日
去重
const arr = [1,2,3,3,1,4];
[...new Set(arr)]; // [1, 2, 3, 4]
Array.from(new Set(arr)); // [1, 2, 3, 4]
[...new Set('ababbc')].join(''); // "abc" 字符串去重
new Set('ice doughnut'); //Set(11) {"i", "c", "e", " ", "d", …}
并集
const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);
const union = new Set([...a, ...b]); // {1, 2, 3, 4}
交集
const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);
const intersect = new Set([...a].filter(x => b.has(x))); // {2, 3}
差集
const a = new Set([1, 2, 3]);
const b = new Set([4, 3, 2]);
const difference = new Set([...a].filter(x => !b.has(x))); // {1}