并集:
const arr1 = [1, 2, 3, 2, 5]; const arr2 = [1, 4, 6, 8, 3]; // 将两个数组合并 const concatArr = [...arr1, ...arr2]; // 对数组去重 const set = new Set(concatArr); const newArr = [...set]
交集:
const arr1 = [1, 2, 3, 2, 5]; const arr2 = [1, 4, 6, 8, 3]; const set1 = new Set(arr1); const set2 = new Set(arr2); const newArr = [...set1].filter(item => { return set2.has(item); });
差集:
const arr1 = [1, 2, 3, 2, 5]; const arr2 = [1, 4, 6, 8, 3]; // 首先用ES6的set给数组去重: const set1 = new Set(arr1); const set2 = new Set(arr2); // 然后分别取出set1中存在,set2中不存在 和 set2中存在,set1中不存在的值 const newArr1 = [...set1].filter((item) => { return !set2.has(item); }); const newArr2 = [...set2].filter(item => { return !set1.has(item); }); // 再将得到的两个新数组合并,就能得到差集了 const newArr = [...newArr1,...newArr2];