如何用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
相关产品推荐
相关产品推荐

