rotem-horovitz
    _hello_about-me_blog_snippets_projects_games
find me in:
privacy
← Back to snippets

chunk

Split an array into fixed-size sub-arrays. The final chunk holds the remainder when the length isn't a clean multiple.

May 20, 2026
utilityarrays

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.