1,并集
let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
//1
let arr = Array.from(new Set([...a, ...b]));
//2
const union= [...new Set([...a,...b])]
console.log('arr',arr);
2.交集
let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
//1
let arr = Array.from(new Set([...b].filter(x => a.has(x))));
//2 遍历第一个数组,且它在第二数组存在
const cross = [...new Set([...a.filter((item)=> b.includer(item))])]
3.差集
let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
let arr = Array.from(new Set([...b].filter(x => !a.has(x))));
console.log('arr',arr);
const union= [...new Set([...a,...b])]
const cross = [...new Set([...a.filter((item)=> b.includer(item))])]
const diff = [...new Set(union.filter((item)=> !cross.includes(item)))]
4.数组对象交集
let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];
let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];
let arr = [...b].filter(x => [...a].some(y => y.id === x.id));
console.log('arr',arr)
5.数组对接差集
let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];
let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];
let arr = [...b].filter(x => [...a].every(y => y.id !== x.id));
console.log('arr',arr);
转载于ES6数组:两个数组或数组对象取并集、交集、差集记录贴_webfullstack的博客-CSDN博客_es6 数组取交集