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

JavaScript中移除数组连续重复对象并合并数量的实现

合并数组中连续同类型对象的数量

给定一个包含产品对象的数组,其中存在连续重复的产品(依据type字段判断)。需要移除连续重复的产品对象,将重复对象的qty值累加到最后一个重复对象中。

原数组

let books = [
  { id: "1", type: "D", price: 25, qty: 27},// *
  { id: "2", type: "D", price: 22, qty: 75},// *
  { id: "3", type: "D", price: 21, qty: 19},// *
  { id: "4", type: "D", price: 19, qty: 62},

  { id: "5", type: "U", price: 23, qty: 19},
  { id: "6", type: "D", price: 20, qty: 22},

  { id: "7", type: "U", price: 25, qty: 14},// *
  { id: "8", type: "U", price: 29, qty: 14}
]

预期结果

[
  { id: "4", type: "D", price: 19, qty: 121},
  { id: "5", type: "U", price: 23, qty: 19},
  { id: "6", type: "D", price: 20, qty: 22},
  { id: "8", type: "U", price: 29, qty: 28}
]

解决方案

可以用数组的reduce方法高效处理这个需求,遍历数组时维护一个结果集合,判断当前元素与结果最后一个元素的类型是否一致,一致则累加数量并保留最后一个元素的属性,否则直接添加新元素。

const mergedBooks = books.reduce((result, current) => {
  const last = result[result.length - 1];
  if (last && last.type === current.type) {
    // 累加数量,并用当前元素的属性覆盖最后一个元素(保留累加后的qty)
    last.qty += current.qty;
    result[result.length - 1] = { ...current, qty: last.qty };
  } else {
    result.push(current);
  }
  return result;
}, []);

这段代码的逻辑:

  • 初始化空数组result作为最终结果容器
  • 遍历每个产品对象current,取出结果数组的最后一个元素last
  • 如果last存在且和current的type相同,就把current的qty加到last的qty上,然后用current的其他属性(id、price)替换last,同时保留累加后的qty
  • 如果类型不同,直接把current加入结果数组

运行后就能得到符合预期的合并结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:58:23