JS - 计算数组的交集、并集、差集、补集

131 阅读1分钟

1. 使用 filter、concat 来计算

const a = [1, 2, 3, 4, 5];
const b = [2, 4, 6, 8, 10];

/**
 * * 1. filter、concat
 */

// 交集
const jj = a.filter(v => b.includes(v));
// console.log(jj); // [ 2, 4 ]

// 并集
const bj = a.filter(v => !b.includes(v)).concat(b);
// console.log(bj); // [1, 3, 5, 2, 4, 6, 8, 10]

// 差集
const cj = a.filter(v => !b.includes(v));
// console.log(cj); // [ 1, 3, 5 ]

// 补集
const buj = a.filter(v => !b.includes(v)).concat(b.filter(v => !a.includes(v)));
// console.log(buj); // [ 1, 3, 5, 6, 8, 10 ]

2. 使用拓展运算符(...)、Set 的特性来计算

const a = [1, 2, 3, 4, 5];
const b = [2, 4, 6, 8, 10];

/**
 * * 2. 拓展运算符(...)、Set
 */

const sa = new Set(a); // { 1, 2, 3, 4, 5 }
const sb = new Set(b); // { 2, 4, 6, 8, 10 }

// 交集
const intersection = a.filter(v => sb.has(v));
// console.log(intersection); // [ 2, 4 ]

// 并集
const union = [...a.filter(v => !sb.has(v)), ...b];
// console.log(union); // [ 1, 3, 5, 6, 8, 10 ]

// 差集
const minus = a.filter(v => !sb.has(v));
// console.log(minus); // [ 1, 3, 5 ]

// 补集
const complement = [...a.filter(v => !sb.has(v)), ...b.filter(v => !sa.has(v))];
// console.log(complement); // [ 1, 3, 5, 6, 8, 10 ]