数组并交差集

现有两数组a = [1, 2, 3]b = [2, 4, 5],求a,b数组的并集,交集和差集

1
2
3
4
5
6
7
8
9
10
11
// 并集
let union = a.concat(b.filter(v => !a.includes(v)));
// [1,2,3,4,5]

// 交集
let intersection = a.filter(v => b.includes(v));
// [2]

// 差集
let difference = a.concat(b).filter(v => !a.includes(v) || !b.includes(v));
// [1,3,4,5]


1
2
3
4
5
// 交集
[[1, 2, 3], [1, 3, 5], [6, 8, 1]].reduce((x, y) => {
return x.filter(el => y.includes(el));
});
// [1]