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

如何从对象数组中筛选出仅含重复ID的去重对象?

解决方案

要实现仅保留数组中ID重复出现的对象,且每个重复ID只保留一个实例的需求,你需要先统计每个ID的出现次数,再基于次数筛选并去重。你之前的代码只做了全局去重,没有过滤掉ID唯一的对象,所以会保留id=3的条目。

方法一:先统计ID出现次数,再筛选去重

let arr1 = [
  {id: 1, name: 'A'},
  {id: 3, name: 'C'},
  {id: 1, name: 'A'},
  {id: 2, name: 'B'},
  {id: 2, name: 'B'}
];

// 1. 统计每个ID的出现次数
const idOccurrences = arr1.reduce((counts, obj) => {
  counts[obj.id] = (counts[obj.id] || 0) + 1;
  return counts;
}, {});

// 2. 筛选出ID重复的对象,同时确保每个ID只保留一个
const newArr = arr1.reduce((result, obj) => {
  // 仅当ID出现次数>=2,且结果数组中还没有该ID时才添加
  if (idOccurrences[obj.id] >= 2 && !result.some(item => item.id === obj.id)) {
    result.push(obj);
  }
  return result;
}, []);

console.log(newArr);
// 输出:[{id: 1, name: 'A'}, {id: 2, name: 'B'}]

方法二:用Map和Set优化性能(适合大数据量)

如果数组规模较大,some方法的遍历会影响性能,可以用Set记录已添加的ID:

let arr1 = [
  {id: 1, name: 'A'},
  {id: 3, name: 'C'},
  {id: 1, name: 'A'},
  {id: 2, name: 'B'},
  {id: 2, name: 'B'}
];

// 统计ID出现次数
const idCountMap = arr1.reduce((map, obj) => {
  map.set(obj.id, (map.get(obj.id) || 0) + 1);
  return map;
}, new Map());

const addedIds = new Set();
const newArr = arr1.filter(obj => {
  const hasDuplicate = idCountMap.get(obj.id) >= 2;
  const notAddedYet = !addedIds.has(obj.id);
  
  if (hasDuplicate && notAddedYet) {
    addedIds.add(obj.id);
    return true;
  }
  return false;
});

console.log(newArr);
// 输出:[{id: 1, name: 'A'}, {id: 2, name: 'B'}]

原代码问题分析

你之前的reduce逻辑只是做了全局去重——只要对象的ID没在结果数组中出现过就添加,不管这个ID在原数组中是否重复。这就导致id=3(仅出现一次)的对象也被保留了,不符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:33:32