Google Script:基于两列统计二维数组重复项并计算汇总
Google Apps Script 实现重复项统计与列求和
功能实现代码
function calculateTotals() { const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); const range = sheet.getDataRange(); const values = range.getValues(); // 跳过表头(假设第一行是表头) const headerRow = values[0]; const dataRows = values.slice(1); // 确定各列的索引(替换成实际表头名称) const targetCol1Index = headerRow.indexOf("对应values[i][1]的列标题"); const targetCol2Index = headerRow.indexOf("对应values[i][2]的列标题"); const flowColIndex = headerRow.indexOf("ig_Flow"); const totalGiftsColIndex = headerRow.indexOf("Total Gifts"); const totalFlowColIndex = headerRow.indexOf("Total Flow"); // 用Map存储分组统计结果:key为"列1值|列2值",value为{count: 重复数量, totalFlow: flow总和} const groupStats = new Map(); // 第一次遍历:统计每个分组的数量和flow总和 dataRows.forEach(row => { const col1Value = row[targetCol1Index]; const col2Value = row[targetCol2Index]; const flowValue = typeof row[flowColIndex] === "number" ? row[flowColIndex] : 0; const groupKey = `${col1Value}|${col2Value}`; if (groupStats.has(groupKey)) { const stats = groupStats.get(groupKey); stats.count += 1; stats.totalFlow += flowValue; } else { groupStats.set(groupKey, { count: 1, totalFlow: flowValue }); } }); // 第二次遍历:填充Total Gifts和Total Flow列 dataRows.forEach(row => { const col1Value = row[targetCol1Index]; const col2Value = row[targetCol2Index]; const groupKey = `${col1Value}|${col2Value}`; const stats = groupStats.get(groupKey); row[totalGiftsColIndex] = stats.count; row[totalFlowColIndex] = stats.totalFlow; }); // 将处理后的数据写回表格 range.setValues([headerRow, ...dataRows]); }
代码说明
- 表头索引匹配:通过表头名称获取列索引,避免硬编码索引的适配问题,需替换代码中
对应values[i][1]的列标题和对应values[i][2]的列标题为表格实际表头。 - 分组统计逻辑:使用
Map存储分组唯一键(两列值拼接)对应的统计数据,一次遍历完成重复数量统计和ig_Flow求和。 - 数据兼容处理:对
ig_Flow列做数字类型校验,非数字值按0处理,避免求和报错。 - 结果填充:二次遍历原数据行,根据分组键取出统计结果,写入目标列。
可选调整:连续重复项统计
若需求是仅统计相邻行满足条件的重复次数(而非同分组总行数),替换统计逻辑为:
// 连续重复项统计逻辑 let lastGroupKey = null; let currentRepeatCount = 1; dataRows.forEach((row, index) => { const col1Value = row[targetCol1Index]; const col2Value = row[targetCol2Index]; const groupKey = `${col1Value}|${col2Value}`; if (index > 0 && groupKey === lastGroupKey) { currentRepeatCount += 1; } else { currentRepeatCount = 1; } row[totalGiftsColIndex] = currentRepeatCount; lastGroupKey = groupKey; });
内容的提问来源于stack exchange,提问作者Einarr
相关产品推荐
相关产品推荐

