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

JS实现数组中相同userId对象合并及total值累加求和的方法

解决方案

你可以通过「分组累加+格式转换」两步实现需求,使用Map存储分组可以天然保留userId首次出现的顺序,和你需要的输出顺序完全匹配。

完整实现代码

const orders = [
  { id: '1', userId: '3', total: 300 },
  { id: '2', userId: '4', total: 200 },
  { id: '3', userId: '5', total: 101 },
  { id: '4', userId: '6', total: 80 },
  { id: '5', userId: '7', total: 76 },
  { id: '6', userId: '8', total: 44 },
  { id: '7', userId: '9', total: 1000 },
  { id: '8', userId: '10', total: 99 },
  { id: '9', userId: '3', total: 65 },
  { id: '10', userId: '4', total: 22 }
];

// 第一步:按userId分组累加total
const userTotalMap = orders.reduce((map, order) => {
  const currentTotal = map.get(order.userId) || 0;
  return map.set(order.userId, currentTotal + order.total);
}, new Map());

// 第二步:转换为目标格式的数组,id按顺序生成
const newOrdersArray = Array.from(userTotalMap, ([userId, total], idx) => ({
  id: String(idx + 1),
  userId,
  total
}));

输出验证

执行后newOrdersArray的结构和你给出的预期结果完全一致:

[
  { id: '1', userId: '3', total: 365 },
  { id: '2', userId: '4', total: 222 },
  { id: '3', userId: '5', total: 101 },
  { id: '4', userId: '6', total: 80 },
  { id: '5', userId: '7', total: 76 },
  { id: '6', userId: '8', total: 44 },
  { id: '7', userId: '9', total: 1000 },
  { id: '8', userId: '10', total: 99 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:45:04