js的Es6取并集,交集,差集
原创
©著作权归作者所有:来自51CTO博客作者未来音律的原创作品,请联系作者获取转载授权,否则将追究法律责任
let a = [1, 2, 3, 4]
console.log(a)
let b = [2, 4, 5]
let aSet = new Set(a)
let bSet = new Set(b)
// 并集
let union = Array.from(new Set(a.concat(b))) // [1,2,3,4,5]
console.log(union)
// 交集
let intersection = Array.from(new Set(a.filter(v => bSet.has(v))))// [2,4]
// 差集
let diff = Array.from(new Set(a.concat(b).filter(v => aSet.has(v) && !bSet.has(v)))
)//[1,3]
console.log(diff)
//找出两个数组并集
function getUnion(arr1, arr2) {
let aSet = new Set(arr1);
let bSet = new Set(arr2);
// 并集
let union = Array.from(new Set(arr1.concat(arr2)));
return union;
}
//找出两个数组的差集
function getDiff(arr1, arr2) {
let aSet = new Set(arr1);
let bSet = new Set(arr2);
// 并集
let diff = Array.from(
new Set(arr1.concat(arr2).filter(v => aSet.has(v) && !bSet.has(v)))
);
return diff;
}
//找出两个数组的交集
function getInter(arr1, arr2) {
let aSet = new Set(arr1);
let bSet = new Set(arr2);
let inter = Array.from(new Set(aSet.filter(v => bSet.has(v))));
return inter;
}