chunk divides an array into batches of size elements. The last batch may be shorter than size if the input length doesn't divide evenly. Throws a RangeError on non-positive sizes so misuse fails loudly.
export function chunk<T>(arr: T[], size: number): T[][] {
if (size <= 0) throw new RangeError('Chunk size must be greater than 0');
const result: T[][] = [];
for (let index = 0; index < arr.length; index += size) {
result.push(arr.slice(index, index + size));
}
return result;
}
Common uses
- Paginating large arrays for batched rendering or API calls.
- Building grid rows from a flat list of cells.
- Rate-limiting bulk operations by processing a fixed number per tick.