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

如何基于另一个数组的id值拆分出对应分组子数组?

按ID分组对象数组的实现方案

你可以通过Array.prototype.reduce()实现按id属性分组,将相同id的对象聚合到同一数组中,再通过Object.values()提取分组后的数组列表,完全满足你的需求。

核心代码实现

var array = 
  [
    { id: "BG", qty: 100 }, 
    { id: "BG", qty: 35 }, 
    { id: "JP", qty: 75 },
    { id: "JP", qty: 50 }
 ];

// 第一步:按id分组,生成以id为键的对象
const groupedById = array.reduce((accumulator, currentItem) => {
  // 若当前id对应的数组未初始化,先创建空数组
  if (!accumulator[currentItem.id]) {
    accumulator[currentItem.id] = [];
  }
  // 将当前对象推入对应id的数组
  accumulator[currentItem.id].push(currentItem);
  return accumulator;
}, {});

// 第二步:提取所有分组后的数组,得到最终结果
const groupedArrays = Object.values(groupedById);

运行结果

groupedArrays就是你期望的数组集合:

[
  [
    { id: "BG", qty: 100 },
    { id: "BG", qty: 35 }
  ],
  [
    { id: "JP", qty: 75 },
    { id: "JP", qty: 50 }
  ]
]

单独获取指定分组

如果需要单独拿到某一组的数组,直接从groupedById对象中取值即可:

const bgGroup = groupedById.BG; // 得到BG分组的数组
const jpGroup = groupedById.JP; // 得到JP分组的数组

补充说明

你之前使用Set的方式只能提取出唯一的id值,无法保留对应的对象数据。而reduce方法可以遍历整个数组,同时完成分组和数据聚合的操作,更适合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:40:39