apps-script-utils 2.1.1 Help

chunk

function chunk<T>(array: T[], size: number = 1): Array<T[]>;

chunk walks the array once and slices it into groups of size elements. When the length does not divide evenly, the final group holds the remainder and is shorter than the rest. The input array is never modified.

Both arguments are validated before any work happens: a non-array input or a fractional size throws instead of returning a quietly wrong result. A size of 0 or less, and an empty input, both produce [] rather than a group of empty groups.

Parameters

Parameter

Type

Description

array

T[]

The array to split. Left untouched.

size (optional) = 1

number

The length of each group. An integer; defaults to 1.

Returns

Array<T[]> — a new array of groups. Every group but the last has exactly size elements.

Throws

Exception

Condition

TypeError

array is not an array.

TypeError

size is not an integer.

Examples

Splitting into fixed-size groups

chunk(["a", "b", "c", "d"], 2); // => [["a", "b"], ["c", "d"]] chunk(["a", "b", "c", "d", "e"], 2); // => [["a", "b"], ["c", "d"], ["e"]]

Writing a large range in batches

A single setValues call with tens of thousands of rows is the usual cause of an exceeded execution time. Splitting the data keeps each call small and each write independently recoverable.

/** * Appends rows in batches, so that one oversized `setValues` call cannot * exhaust the execution time limit. */ export function appendRows(sheet: GoogleAppsScript.Spreadsheet.Sheet, rows: string[][]): void { for (const batch of chunk(rows, 500)) { sheet.getRange(sheet.getLastRow() + 1, 1, batch.length, batch[0].length).setValues(batch); } }
function appendRows(sheet, rows) { for (const batch of chunk(rows, 500)) { sheet.getRange(sheet.getLastRow() + 1, 1, batch.length, batch[0].length).setValues(batch); } }

Edge cases

chunk([1, 2, 3]); // => [[1], [2], [3]] — size defaults to 1 chunk([], 2); // => [] chunk([1, 2, 3], 0); // => [] chunk("a,b,c", 2); // throws TypeError: Input 'array' must be an array. chunk([1, 2, 3], 1.5); // throws TypeError: Input 'size' must be an integer.

See also

Source

src/lang/array/chunk.ts

23 September 2026

This documentation was generated with AI (Claude) from the library's source code.