ES6数组:两个数组或数组对象取并集、交集、差集记录贴
数组
取并集
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([…a, …b]));
console.log(‘arr’,arr);
结果
取交集
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))));
结果
取差集
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);
结果
数组对象
取交集
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)
结果
取差集
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);
结果:
————————————————
版权声明:本文为CSDN博主「webfullstack」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/webfullstack/article/details/90041587