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

如何检查对象数组中的元素是否存在于另一个对象数组中

实现思路

  • 先将对比目标数组的id提取为Set结构,将查找复杂度降到O(1)
  • 取两个数组的最大长度作为遍历次数
  • 遍历过程中如果当前索引超出任意一个数组的长度,直接返回false,否则检查对应元素是否存在

完整实现代码

const arr1 = [{id: 1},{id: 2}]
const arr2 = [{id: 1},{id: 4},{id: 3}]

// 提取arr2所有id存入Set,便于快速查找
const arr2IdSet = new Set(arr2.map(item => item.id))
// 取两个数组最大长度
const maxLength = Math.max(arr1.length, arr2.length)
const res = []

for (let i = 0; i < maxLength; i++) {
  // 索引超出任意一个数组长度直接返回false
  if (i >= arr1.length || i >= arr2.length) {
    res.push(false)
    continue
  }
  // 检查当前索引arr1元素是否存在于arr2中
  res.push(arr2IdSet.has(arr1[i].id))
}

console.log(res) // 输出 [true, false, false]

如果需要双向校验(即同一索引下的两个元素都要在对方数组中存在才返回true),可以把判断逻辑修改为:

// 提前提取arr1的id集合
const arr1IdSet = new Set(arr1.map(item => item.id))
// 原有判断逻辑替换为以下内容
res.push(arr2IdSet.has(arr1[i].id) && arr1IdSet.has(arr2[i].id))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 20:54:08