const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const b = [5, 6, 7, 8, 9, 10, 11, 12, 13];
/**
* 并集
* 将两个数组合并,并用new Set去重
* 会得到一个Set对象,{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }
* 需要用Array.from转换成数组
* (并集就是合并去重)
*/
const union = Array.from(new Set([...a, ...b]));
console.log('并集======', union);
/**
* 交集
* 用filter方法筛选出a数组中的元素,在b数组中存在的元素
* 并用new Set去重
* 用Array.from转换成数组
* (交集就是把一样的元素找出来)
*/
const cross = Array.from(new Set(a.filter((item) => b.includes(item))));
console.log('交集======', cross);
/**
* 差集
* (差集就是把并集和交集的元素都去掉,剩下的就是差集)
*/
const diff = Array.from(new Set(union.filter((item) => !cross.includes(item))));
console.log('差集======', diff);
结果.png