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

如何对比不同字段的两个数组并移除匹配的数组对象?

解决方法

要实现以不同字段匹配ID,并从目标数组中移除对应对象的需求,可按以下步骤操作:

  • 提取待排除ID集合:先将Array2中所有SystemId提取到Set集合中,大幅提升后续匹配查找的效率。
  • 过滤目标数组:使用filter方法遍历Array1,仅保留OrderId不在排除集合中的对象。

代码实现

const Array1 = [
  {
    "OrderId": "00111111",
    "BillingCountry": "GB",
    "CurrencyIsoCode": "GBP",
    "PersonEmail": "testing1@yahoo.com"   
  },
  {
    "OrderId": "00222222",
    "BillingCountry": "US",
    "CurrencyIsoCode": "USD",
    "PersonEmail": "testing2@yahoo.com"     
  }
];

const Array2 = [
  {
    "SystemId": "00111111" 
  },
  {
    "SystemId": "00333333" 
  },
  {
    "SystemId": "00444444" 
  }
];

// 提取Array2中的SystemId到Set
const excludedIds = new Set(Array2.map(item => item.SystemId));

// 过滤Array1,移除ID匹配的对象
const result = Array1.filter(item => !excludedIds.has(item.OrderId));

console.log(result);

运行结果

[
  {
    "OrderId": "00222222",
    "BillingCountry": "US",
    "CurrencyIsoCode": "USD",
    "PersonEmail": "testing2@yahoo.com"     
  }
]

这种方案的时间复杂度为O(n + m)(n为Array1长度,m为Array2长度),相比嵌套循环的O(n*m)效率更高,适合处理大规模数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:52:15