Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active May 21, 2022
Embed
What would you like to do?
Splitting and Processing an Array every n length using Google Apps Script

Splitting and Processing an Array every n length using Google Apps Script

This is a sample script for splitting and processing an array every n length using Google Apps Script. When I prepare a sample script with Google Apps Script, I sometimes have the situation that it is required to split and process an array every n length. This sample script is for achieving this situation.

Please set limit. This sample script splits the sample array every 3 length.

When you use this script with Google Apps Script, please enable V8 runtime.

Sample script 1

This sample script uses the while loop.

function sample1() {
  const ar = ["a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", "i1", "j1"];

  const limit = 3; // Please set the number.
  const res = [];
  while (ar.length) {
    res.push(ar.splice(0, limit).map((e) => "updated_" + e));
  }
  console.log(res);
}

Sample script 2

This sample script uses the map. This process cost is lower than that of the above one.

function sample2() {
  const ar = ["a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", "i1", "j1"];

  const limit = 3; // Please set the number.
  const res = [...Array(Math.ceil(ar.length / limit))].map((_) => ar.splice(0, limit).map((e) => "updated_" + e));
  console.log(res);
}

Result

The result of both sample script is as follows.

[
  ["updated_a1", "updated_b1", "updated_c1"],
  ["updated_d1", "updated_e1", "updated_f1"],
  ["updated_g1", "updated_h1", "updated_i1"],
  ["updated_j1"]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment