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

如何在JavaScript中提取主数组所有子数组中重复的对象

筛选所有子数组共有的重复对象

需要实现一个函数,筛选出主数组中所有子数组都包含的重复对象。示例数组如下:

const array = [
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86405}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86407}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86409}]
];

期望返回结果:[{"post_id": 86403},{"post_id": 86404}]

现有代码的问题

找到一段处理字符串数组的代码,但它存在两个明显局限:一是需要手动定义多个子数组再合并,不够动态;二是只能处理字符串类型,无法直接判断对象是否重复:

var array1 = ["Lorem", "ipsum", "dolor"],
    array2 = ["Lorem", "ipsum", "quick", "brown", "foo"],
    array3 = ["Jumps", "Over", "Lazy", "Lorem"],
    array4 = [1337, 420, 666, "Lorem"],
    data = [array1, array2, array3, array4],
    result = data.reduce((a, b) => a.filter(c => b.includes(c)));

console.log(result);

解决方案

针对对象数组的特性,我们需要自定义对象相等的判断逻辑(通过对象的唯一标识字段,比如post_id),同时实现动态处理任意数量子数组的函数:

function findCommonObjects(mainArray, uniqueKey) {
  if (!mainArray.length) return [];
  
  // 以第一个子数组为基准,逐步与后续子数组求交集
  return mainArray.reduce((commonItems, currentSubArr) => {
    return commonItems.filter(item => {
      // 检查当前子数组中是否存在拥有相同唯一标识的对象
      return currentSubArr.some(subItem => subItem[uniqueKey] === item[uniqueKey]);
    });
  });
}

// 测试示例
const targetArray = [
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86405}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86407}],
  [{"post_id": 86403},{"post_id": 86404},{"post_id": 86409}]
];

console.log(findCommonObjects(targetArray, 'post_id'));
// 输出: [{"post_id": 86403},{"post_id": 86404}]

函数说明

  • 动态适配:无需手动定义单个子数组,直接传入包含任意数量子数组的主数组即可
  • 通用判断:通过指定uniqueKey(如post_id)来识别重复对象,适用于各类带唯一标识的对象数组
  • 高效逻辑:利用reduce逐步缩小范围,每次只保留当前所有子数组共有的对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:10:27