Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created August 18, 2022 05:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/9970ebf1bd3c7475df57126f5d544f89 to your computer and use it in GitHub Desktop.
Save tanaikech/9970ebf1bd3c7475df57126f5d544f89 to your computer and use it in GitHub Desktop.
Updating Destination Sheet by Source Sheet in Google Spreadsheet using Google Apps Script

Updating Destination Sheet by Source Sheet in Google Spreadsheet using Google Apps Script

This is a sample script for updating the destination sheet by the source sheet in Google Spreadsheet using Google Apps Script.

The sample situation is as follows.

Sample script

function myFunction() {
  const sheetNames = ["Sheet1", "Sheet2"];

  // Retrieve values from source and destination sheets.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const [srcSheet, dstSheet] = sheetNames.map((s) => ss.getSheetByName(s));
  const [srcValues, dstValues] = [srcSheet, dstSheet].map((s) =>
    s.getDataRange().getValues()
  );

  // Create an array for updating the destination sheet.
  const srcObj = srcValues.reduce((o, r) => ((o[r[0]] = r), o), {});
  const values = [
    ...dstValues.map(([a, ...v]) => {
      if (srcObj[a]) {
        const temp = srcObj[a];
        delete srcObj[a];
        return temp;
      }
      return [a, ...v];
    }),
    ...Object.values(srcObj),
  ];

  // Update the destination sheet.
  dstSheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}
  • In this sample script, "Sheet1" and "Sheet2" are the source and destination sheets, respectively.

  • When this script is run, the top image is obtained.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment