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

如何在ES6 JavaScript中获取两个对象数组的相同交集元素

实现方案

方案1:高性能版(推荐,时间复杂度O(n+m))

先将第二个数组的对象特征存入Set做快速匹配,再用filter过滤第一个数组:

const test = [
    { firstName: "John", lastName: "Doe" },
    { firstName: "Michael", lastName: "Sins" },
    { firstName: "Alex", lastName: "Brown" }
  ];
const test2 = [
    { firstName: "Lisa", lastName: "Shore" },
    { firstName: "John", lastName: "Doe" },
    { firstName: "Justin", lastName: "Park" },
  ];

// 生成test2的唯一标识集合
const test2IdentifierSet = new Set(test2.map(item => `${item.firstName}_${item.lastName}`))
// 过滤匹配的元素
const intersection = test.filter(item => test2IdentifierSet.has(`${item.firstName}_${item.lastName}`))

console.log(intersection) // 输出 [{ firstName: "John", lastName: "Doe" }]
  • 该方案适合数据量较大的场景,Set的查找效率为O(1),远优于双重循环。
  • 如果对象字段较多且结构固定,可以替换拼接规则为JSON.stringify(item),注意要保证两个数组的对象字段顺序一致。

方案2:简洁直观版(适合小数据量)

直接使用filter结合some双重匹配:

const intersection = test.filter(item => 
  test2.some(el => el.firstName === item.firstName && el.lastName === item.lastName)
)
  • 写法更直白易读,数据量不大时完全够用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:15:03