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

合并相邻同theaterID对象的price值:对象数组处理技术需求

合并相邻同theaterID的对象(Price求和)

这个需求的核心是仅合并相邻且theaterID相同的项——不是把数组里所有同ID的元素全部聚合,这点一定要先明确,避免理解偏差。

我给你提供一个JavaScript的实现方案,逻辑直白易懂,还能保证处理效率:

核心思路

  • 先初始化一个空的结果数组,用来存放处理后的最终对象
  • 遍历原数组的每一项:
    1. 如果结果数组为空,直接把当前元素加入结果数组
    2. 如果结果数组最后一项的theaterID和当前项一致,就把当前项的price累加到最后一项的price上
    3. 如果ID不同,就把当前项作为新对象添加到结果数组末尾

代码实现

function mergeAdjacentTheaters(theaterArray) {
  // 空数组直接返回,避免后续报错
  if (!theaterArray.length) return [];
  
  // 浅拷贝第一个元素,防止修改原数组的原始数据
  const mergedResult = [ {...theaterArray[0]} ];
  
  for (let i = 1; i < theaterArray.length; i++) {
    const currentItem = theaterArray[i];
    const lastMergedItem = mergedResult[mergedResult.length - 1];
    
    if (lastMergedItem.theaterID === currentItem.theaterID) {
      // 相邻同ID,累加价格
      lastMergedItem.price += currentItem.price;
    } else {
      // 不同ID,新增合并项
      mergedResult.push({...currentItem});
    }
  }
  
  return mergedResult;
}

// 测试用例
const testData = [
  { theaterID: 1, price: 10 },
  { theaterID: 1, price: 20 },
  { theaterID: 2, price: 15 },
  { theaterID: 1, price: 5 },
  { theaterID: 2, price: 25 },
  { theaterID: 2, price: 10 }
];

console.log(mergeAdjacentTheaters(testData));
// 输出结果:
// [
//   { theaterID: 1, price: 30 },
//   { theaterID: 2, price: 15 },
//   { theaterID: 1, price: 5 },
//   { theaterID: 2, price: 35 }
// ]

额外注意事项

  • 代码里用{...currentItem}做浅拷贝,是为了不改动原数组的原始数据,如果业务不需要保留原数组,也可以直接传入currentItem,但浅拷贝的写法更安全
  • 如果你的price是字符串类型(比如接口返回的字符串数字),记得先转成数字再累加,比如改成lastMergedItem.price += Number(currentItem.price)
  • 这个算法的时间复杂度是O(n),只需要遍历一次数组,处理效率拉满

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:40:40