Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active May 11, 2023 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/05e5fd84561080e484bd4df799862f01 to your computer and use it in GitHub Desktop.
Save tanaikech/05e5fd84561080e484bd4df799862f01 to your computer and use it in GitHub Desktop.
Unpivot on Google Spreadsheet using Google Apps Script

Unpivot on Google Spreadsheet using Google Apps Script

This is a sample script for converting the values on Google Spreadsheet as unpivot (reverse pivot) using Google Apps Script.

Sample script 1:

const SAMPLE1 = ([[, ...header], ...values]) =>
  header.flatMap((h, i) => values.map((t) => [h, t[0], t[i + 1]]));
  • In the sample, the source data is "A1:D8". And, a custom function of =SAMPLE1(A1:D8) is put into "F1".
  • When this script is used, the result showing the above image (most left table to middle table) is obtained.

Sample script 2:

const SAMPLE2 = v => {
  const [a, b, c] = v[0].map((_, c) => v.map(r => r[c]));
  const ch = [...new Set(a)];
  const rh = [...new Set(b)];
  const size = rh.length;
  const values = [...Array(Math.ceil(c.length / size))].map(_ => c.splice(0, size));
  const temp = [[null, ...rh], ...values.map((vv, i) => [ch[i], ...vv])];
  return temp[0].map((_, c) => temp.map(r => r[c]));
}
  • In the sample, the source data is "F1:H21". And, a custom function of =SAMPLE2(F1:H21) is put into "J1".
  • When this script is used, the result showing the above image (middle table to most right table) is obtained.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment