Split Array by n Elements using Google Apps Script

Gists

This is a sample script for splitting an array by n elements using Google Apps Script.

Sample script 1:

var limit = 3;
var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var res = [];
while (ar.length > 0) res.push(ar.splice(0, limit));
Logger.log(res); // [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0]]

Above sample script is a simple. But at Google Apps Script, the process cost of “while” is higher than the for loop as shown in this report. So I recommend the following sample script for Google Apps Script.

Sample script 2:

var limit = 3;
var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var res = [];
var len = ar.length;
for (var i = 0; i < len; i++) {
  res.push(ar.splice(0, limit));
  len -= limit - 1;
}
Logger.log(res); // [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0]]

 Share!