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

遍历Google Sheets二维数组生成日期与ID对应条目方案

实现学生-日期全量组合并匹配作业数据(Google Apps Script)

核心思路落地代码

假设你已经有了处理好的二维数组 processedData(结构:[ID, Name, Assignments, Date, Overall Grade]),以及存放日期列表的工作表(示例命名为「日期表」),下面是具体实现代码:


1. 构建学生信息映射与作业数据索引

先把已有数据转成高效查询的结构,避免嵌套循环里重复遍历数组:

// 1. 提取唯一学生ID与对应姓名(确保同ID姓名统一)
const studentMap = new Map();
// 2. 构建学生+日期的作业数据索引,快速查找匹配记录
const assignmentIndex = new Map();

processedData.forEach(row => {
  const [id, name, assignments, date, overallGrade] = row;
  // 存学生ID-姓名映射
  if (!studentMap.has(id)) {
    studentMap.set(id, name);
  }
  // 用「ID|日期字符串」作为索引键,存作业和总分数据
  const indexKey = `${id}|${date.toISOString()}`;
  assignmentIndex.set(indexKey, { assignments, overallGrade });
});

// 提取唯一学生ID列表
const uniqueStudentIds = Array.from(studentMap.keys());

2. 获取日期列表

从指定工作表读取并过滤有效日期:

const dateSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('日期表');
// 读取日期列数据(假设日期在A列,可根据实际调整)
const dateList = dateSheet.getDataRange().getValues()
  .flat() // 转一维数组
  .filter(value => value instanceof Date) // 只保留有效日期
  .sort((a, b) => a - b); // 按日期升序排序

3. 生成全量组合并填充数据

嵌套循环生成学生-日期的所有组合,匹配已有数据填充,无数据则留空:

const result = [];

// 外层循环:遍历每个学生
uniqueStudentIds.forEach(id => {
  const name = studentMap.get(id);
  // 内层循环:遍历每个日期
  dateList.forEach(date => {
    const indexKey = `${id}|${date.toISOString()}`;
    const matchedData = assignmentIndex.get(indexKey);
    
    // 组装结果行:ID, Name, Assignments, Date, Overall Grade
    result.push([
      id,
      name,
      matchedData ? matchedData.assignments : '', // 无数据留空
      date,
      matchedData ? matchedData.overallGrade : '' // 无数据留空
    ]);
  });
});

// 按学生ID、日期排序(如果需要更严格的排序,可调整排序逻辑)
result.sort((a, b) => {
  // 先按学生ID排序
  if (a[0] !== b[0]) return a[0].localeCompare(b[0]);
  // ID相同则按日期排序
  return a[3] - b[3];
});

// 可选:将结果写入新工作表
const outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('输出表');
outputSheet.clearContents();
outputSheet.getRange(1, 1, result.length, result[0].length).setValues(result);

关键说明

  • 用Map做索引是为了把查找时间从O(n)降到O(1),数据量大时效率提升明显
  • 日期用toISOString()作为索引键,避免因日期对象引用不同导致匹配失败
  • 排序逻辑可根据需求调整,比如按姓名排序而非ID

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:55:19