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

如何用JavaScript按日期分组累加财务数据并在每组末尾插入合计行

JavaScript实现按日期分组累加并插入合计行

实现逻辑

  • 单次遍历原始报表数组,按日期累计收款、存款总额
  • 遇到日期切换时插入上一日期的合计行,遍历结束后补最后一个日期的合计行
  • 自动处理null值和字符串类型的数值,空值按0计算

示例代码

function insertDailyTotal(reportData) {
  const processedData = []
  let currentDate = null
  let collectSum = 0
  let depositSum = 0

  reportData.forEach((item, idx) => {
    // 日期变更时插入上一日的合计
    if (currentDate && item.date !== currentDate) {
      processedData.push({
        date: currentDate,
        name_of_collection: 'Total',
        collection: collectSum,
        deposit: String(depositSum)
      })
      // 重置累计值
      collectSum = 0
      depositSum = 0
    }

    // 累加当日数值
    collectSum += Number(item.collection || 0)
    depositSum += Number(item.deposit || 0)
    // 存入原始条目
    processedData.push({...item})
    currentDate = item.date

    // 处理最后一条数据的合计
    if (idx === reportData.length - 1) {
      processedData.push({
        date: currentDate,
        name_of_collection: 'Total',
        collection: collectSum,
        deposit: String(depositSum)
      })
    }
  })
  return processedData
}

// 调用方法替换原数组
this.GeneratedFinancialReport = insertDailyTotal(this.GeneratedFinancialReport)

适配说明

如果不需要deposit字段为字符串格式,只需要删除代码中String()的包裹即可,合计的两个字段都会返回数字类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:48:03