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.
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);
}
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);
}
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"]
]