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

如何从对象数组中提取title重复且_id不重复的对象

提取数组中title重复且_id唯一的对象的实现方法

给定对象数组products,需要筛选出title属性值重复出现的对象组成新数组,同时确保新数组里的_id完全不重复(避免同一个_id的对象重复加入)。先看示例:
原数组:

products = [{_id:1234,title:'carrot',price:90},{_id:345,title:'Beans',price:100},{_id:789,title:'carrot',price:100}]

期望结果:

result = [{_id:1234,title:'carrot',price:90},{_id:789,title:'carrot',price:100}]

下面是几种实用的实现方式:

方法1:用Map分组+去重

先按title把对象分组,同时用Set记录已加入的_id避免重复,最后只保留分组内元素数量≥2的组(也就是title重复出现的),展开成结果数组:

const products = [{_id:1234,title:'carrot',price:90},{_id:345,title:'Beans',price:100},{_id:789,title:'carrot',price:100}, {_id:1234,title:'carrot',price:95}];

const titleGroup = new Map();
const addedIds = new Set();

products.forEach(item => {
  // 跳过已存在的_id
  if (addedIds.has(item._id)) return;
  addedIds.add(item._id);
  
  // 按title分组
  if (!titleGroup.has(item.title)) {
    titleGroup.set(item.title, []);
  }
  titleGroup.get(item.title).push(item);
});

// 筛选出title重复的组并展开
const result = [];
for (const [_, items] of titleGroup) {
  if (items.length > 1) {
    result.push(...items);
  }
}

console.log(result);

方法2:用普通对象分组+去重

和Map思路一致,只是用普通对象存储分组,代码更简洁:

const products = [{_id:1234,title:'carrot',price:90},{_id:345,title:'Beans',price:100},{_id:789,title:'carrot',price:100}, {_id:1234,title:'carrot',price:95}];

const groups = {};
const existingIds = new Set();

products.forEach(item => {
  if (existingIds.has(item._id)) return;
  existingIds.add(item._id);
  
  const titleKey = item.title;
  groups[titleKey] ? groups[titleKey].push(item) : groups[titleKey] = [item];
});

// 筛选并拼接结果
const result = Object.values(groups).filter(group => group.length > 1).flat();

console.log(result);

方法3:先统计title频次再筛选

先遍历一次数组统计每个title的出现次数,再遍历一次筛选出符合条件的对象,同时用Set去重_id:

const products = [{_id:1234,title:'carrot',price:90},{_id:345,title:'Beans',price:100},{_id:789,title:'carrot',price:100}, {_id:1234,title:'carrot',price:95}];

// 统计每个title出现的次数
const titleCount = {};
products.forEach(item => {
  titleCount[item.title] = (titleCount[item.title] || 0) + 1;
});

const result = [];
const usedIds = new Set();

products.forEach(item => {
  // 只保留title重复且_id未被使用过的对象
  if (titleCount[item.title] > 1 && !usedIds.has(item._id)) {
    result.push(item);
    usedIds.add(item._id);
  }
});

console.log(result);

简化版(已知原数组_id唯一)

如果你的products数组里的_id本身就是唯一的(比如从数据库查询的结果),可以去掉去重逻辑,代码更简洁:

const products = [{_id:1234,title:'carrot',price:90},{_id:345,title:'Beans',price:100},{_id:789,title:'carrot',price:100}];

const titleGroup = new Map();
products.forEach(item => {
  titleGroup.set(item.title, [...(titleGroup.get(item.title) || []), item]);
});

const result = Array.from(titleGroup.values()).filter(g => g.length > 1).flat();
console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:10:48