You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TypeScript筛选数组差集:获取arrayB中不存在的元素

TypeScript 计算对象数组的差集

给定两个对象数组,我们需要筛选出所有存在于arrayA但不存在于arrayB的元素,判断依据为对象的id字段。

实现思路

先把arrayB中所有元素的id提取到一个Set集合里——利用Set的O(1)查找特性提升效率,再遍历arrayA过滤出id不在该集合中的元素,就能得到目标差集。

TypeScript 代码实现

// 定义数组元素的类型
type Item = { id: string };

// 原始数组
const arrayA: Item[] = [
    { "id": "1" },
    { "id": "4" },
    { "id": "7" },
    { "id": "5" }
];

const arrayB: Item[] = [
    { "id": "1" },
    { "id": "5" }
];

// 计算差集
const bIdSet = new Set(arrayB.map(item => item.id));
const difference = arrayA.filter(item => !bIdSet.has(item.id));

// 输出结果
console.log(difference);

运行结果

[
    { "id": "4" },
    { "id": "7" }
]

内容的提问来源于stack exchange,提问作者StormTrooper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:31:05