javascript求两数组差集推荐filter+includes,得a\b;对象数组用some按字段比对;大数据量用set优化性能;对称差集需合并两次单向差集。

JavaScript 找两个数组的差集,本质是找出在数组 A 中存在、但在数组 B 中不存在的元素(即 A \ B)。常用且清晰的方式是用 filter + includes,兼顾可读性与兼容性。
基础方法:filter + includes(推荐)
适用于大多数场景,代码简洁,语义明确,支持重复元素和任意类型(前提是能被 includes 正确比较):
const arr1 = [1, 2, 3, 4]; const arr2 = [3, 4, 5, 6]; const diff = arr1.filter(item => !arr2.includes(item)); // → [1, 2]
- 注意:该方法返回的是 arr1 对 arr2 的单向差集,不是对称差(即不包含 arr2 里有而 arr1 里没有的元素)
- 若需去重,可在 filter 前先用
[...new Set(arr1)]处理 - 对对象数组不适用(
includes比较引用,不是值)
处理对象数组:用 find 或 some 配合属性比对
当数组元素是对象时,需按某个字段(如 id)判断是否“存在”:
const users1 = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
const users2 = [{id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}];
const diffUsers = users1.filter(a =>
!users2.some(b => b.id === a.id)
);
// → [{id: 1, name: 'Alice'}]
- 用
some替代includes,灵活定义“相等逻辑” - 性能敏感时,可先将
users2的 id 提取为 Set:const ids2 = new Set(users2.map(u => u.id)),再用!ids2.has(a.id)
高效方案:Set 优化(大数据量推荐)
当数组较大(比如上千项),用 Set 预处理第二个数组,把 includes 的 O(n) 降为 O(1):
const arr1 = [1, 2, 3, 4, 2]; const arr2 = [3, 4, 5, 6]; const set2 = new Set(arr2); const diff = arr1.filter(item => !set2.has(item)); // → [1, 2, 2](保留原 arr1 的重复和顺序)
- 如果希望结果也去重,最后加一步:
[...new Set(diff)] - Set 只对原始值(number/string/boolean/symbol)或相同引用的对象有效;对象仍需转 key 比较
对称差集(A △ B):只保留“独有”的元素
如果需要的是两个数组中“互不包含”的所有元素(即并集减交集),可合并两次单向差集:
const symmetricDiff = [ ...arr1.filter(x => !arr2.includes(x)), ...arr2.filter(x => !arr1.includes(x)) ]; // → [1, 2, 5, 6]
- 结果含重复?可用
[...new Set(symmetricDiff)]去重 - 更简洁写法(ES2024+):暂无原生对称差集 API,仍需手动组合
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











