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

简化Node.js CSV分组求和代码:按Service Type聚合Net Charge Amount

按Service Type汇总Net Charge Amount的优化实现

不用为每个Service Type单独创建数组和判断逻辑,直接遍历Shipments数组,用对象/Map做分组统计即可,代码简洁且适配任意数量的Service Type:

核心逻辑(以JavaScript为例)

// 初始化统计容器,存储每个Service Type的汇总数据
const serviceStats = {};

// 遍历所有发货记录
Shipments.forEach(item => {
  const type = item['Service Type'];
  const charge = parseFloat(item['Net Charge Amount']);

  // 首次遇到该Service Type时,初始化统计项
  if (!serviceStats[type]) {
    serviceStats[type] = {
      totalNetCharge: 0,
      shipmentCount: 0 // 可选:统计该类型的发货单数量
    };
  }

  // 累加金额和计数
  serviceStats[type].totalNetCharge += charge;
  serviceStats[type].shipmentCount += 1;
});

// 输出最终统计结果
console.log(serviceStats);

逻辑说明

  • 用对象serviceStats的键存储唯一的Service Type,值存储对应的金额总和、发货数量等统计数据
  • 遍历过程中自动识别新的Service Type并初始化,无需提前定义所有类型
  • 所有逻辑集中在一次遍历里,避免冗余代码,扩展性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:33:21