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

如何基于唯一属性对JavaScript对象数组进行分组?(原生JS实现示例)

原生JS实现按id分组并去重name的方案

嘿,这个需求挺典型的,用原生JavaScript完全能搞定,我给你捋个清晰的实现思路和代码:

首先看你的需求:要把重复id的项合并,并且names数组里要去掉重复的名称,最后转成指定的数组结构。我们可以分两步走:

第一步:用reduce做分组+去重

Array.prototype.reduce()是处理这类分组需求的利器,我们可以用它来遍历原数组,同时构建按id分组的对象,顺便做name的去重:

const items = [ 
  { id: 1, name: 'a' }, 
  { id: 2, name: 'b' }, 
  { id: 3, name: 'c' }, 
  { id: 1, name: 'd' }, 
  { id: 3, name: 'f' }, 
  { id: 1, name: 'a' }, 
  { id: 3, name: 'c' }, 
];

// 用reduce构建分组对象
const groupedObj = items.reduce((accumulator, currentItem) => {
  // 如果当前id还没在分组对象里,初始化结构
  if (!accumulator[currentItem.id]) {
    accumulator[currentItem.id] = { id: currentItem.id, names: [] };
  }
  
  // 检查name是否已存在,避免重复添加
  if (!accumulator[currentItem.id].names.includes(currentItem.name)) {
    accumulator[currentItem.id].names.push(currentItem.name);
  }
  
  return accumulator;
}, {}); // 初始值是空对象

这一步执行完后,groupedObj会是这样的结构:

{
  1: { id: 1, names: ['a', 'd'] },
  2: { id: 2, names: ['b'] },
  3: { id: 3, names: ['c', 'f'] }
}

第二步:转成预期的数组格式

现在只需要把分组对象的所有值提取出来,转成数组就行,用Object.values()就能轻松实现:

const result = Object.values(groupedObj);

现在result就是你要的预期结果了,打印出来看看:

console.log(result);
// 输出:
// [ { id: 1, names: ['a', 'd']}, { id: 2, names: ['b']}, { id: 3, names: ['c', 'f']} ]

补充:如果不需要去重怎么办?

要是你不需要对names数组去重,只需要把判断includes的那行代码删掉就行,直接push:

// 去掉去重逻辑的版本
const groupedObj = items.reduce((accumulator, currentItem) => {
  if (!accumulator[currentItem.id]) {
    accumulator[currentItem.id] = { id: currentItem.id, names: [] };
  }
  accumulator[currentItem.id].names.push(currentItem.name);
  return accumulator;
}, {});

这样就完全用原生JS实现了,没有依赖任何外部库,逻辑也很直观~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:52:59