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

使用Google Apps Script基于另一数组替换目标数组指定行

实现方案

注意事项

Google Sheets 中getValues()返回的二维数组索引从0开始,如果你在arraySmall第一列存放的是工作表直观显示的1开头行号,需要做索引偏移,如果你存的已经是arrayBig的对应索引,可忽略偏移步骤。

代码实现

首先将arraySmall转换为映射表提升查找效率,再通过map遍历arrayBig完成替换:

// 生成替换映射表:key为arrayBig的目标索引,value为要替换的行内容
const replaceMap = new Map();
arraySmall.forEach(smallRow => {
  // 行号转数组索引:如果arraySmall第一列是数组索引,删除 -1 即可
  const targetArrayIndex = smallRow[0] - 1;
  // 若不需要保留第一列的行号值,可将smallRow改为smallRow.slice(1)
  replaceMap.set(targetArrayIndex, smallRow);
});

// 遍历大数组完成替换
const updatedArrayBig = arrayBig.map((originRow, currentIndex) => {
  // 当前索引存在替换规则则返回新行,否则返回原行
  return replaceMap.has(currentIndex) ? replaceMap.get(currentIndex) : originRow;
});

补充说明

  • 该方案时间复杂度为O(n+m)(n为arrayBig长度,m为arraySmall长度),适合数据量较大的场景
  • 替换时如果需要保留arrayBig指定行的部分列内容,可以在判断replaceMap.has(currentIndex)为真时,自行拼接原行和新行的对应列即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 13:57:02