const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const b = [5, 6, 7, 8, 9, 10, 11, 12, 13];
/**
* 并集
* 將兩個(gè)數(shù)組合并,并用new Set去重
* 會(huì)得到一個(gè)Set對(duì)象逼蒙,{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }
* 需要用Array.from轉(zhuǎn)換成數(shù)組
* (并集就是合并去重)
*/
const union = Array.from(new Set([...a, ...b]));
console.log('并集======', union);
/**
* 交集
* 用filter方法篩選出a數(shù)組中的元素从绘,在b數(shù)組中存在的元素
* 并用new Set去重
* 用Array.from轉(zhuǎn)換成數(shù)組
* (交集就是把一樣的元素找出來)
*/
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);
結(jié)果.png