JavaScript数组可通过filter、map、includes等方法配合Set模拟集合操作:去重用[...new Set(arr)]或filter+indexOf;并集用[...new Set([...a,...b])];交集用a.filter(item=>b.includes(item))再套Set;差集用a.filter(item=>!b.includes(item))再套Set。

用数组方法做去重(模拟集合唯一性)
数组去重本质是“保留首次出现的元素,跳过后续重复项”。 `filter` + `indexOf` 是最直观的写法:const arr = [1, 2, 2, 3, 4, 4, 5];
const unique = arr.filter((item, index) => arr.indexOf(item) === index);
// 结果:[1, 2, 3, 4, 5]
const unique = [...new Set(arr)];
注意:`Set` 对象对对象或函数等引用类型仍按内存地址判重,数组中含对象时需手动深比较。用数组方法求两个数组的并集
并集 = 所有不重复的元素合在一起。 先合并再去重即可:const a = [1, 2, 3];
const b = [3, 4, 5];
const union = [...new Set([...a, ...b])];
// 结果:[1, 2, 3, 4, 5]
const union = [...a, ...b.filter(item => !a.includes(item))];
用数组方法求交集
交集 = 同时出现在两个数组中的元素(去重后)。 核心是“遍历一个数组,检查是否在另一个中存在”:const a = [1, 2, 3, 4];
const b = [3, 4, 5, 6];
const intersection = a.filter(item => b.includes(item));
// 结果:[3, 4]
const intersection = [...new Set(a.filter(item => b.includes(item)))];
用数组方法求差集(a − b)
差集 = 在 a 中但不在 b 中的元素。 直接过滤即可:const a = [1, 2, 3, 4];
const b = [2, 4, 5];
const difference = a.filter(item => !b.includes(item));
// 结果:[1, 3]
const difference = [...new Set(a.filter(item => !b.includes(item)))];
不复杂但容易忽略细节

















