Skip to content

chunk

Chunks an array into smaller arrays of specified size. null and undefined are treated as empty arrays and return [].

Available since v1.9.0

import { chunk } from '@helpers4/array';
chunk<T>(array: readonly T[] | null | undefined, size: number): T[][]
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe array to chunk
sizenumberThe size of each chunk

T[][] — Array of chunks

Chunks an array of 5 elements into groups of 2, with the last chunk containing the remainder.

chunk([1, 2, 3, 4, 5], 2)
// => [[1, 2], [3, 4], [5]]

When the array length is evenly divisible by the chunk size, all chunks are equal.

chunk([1, 2, 3, 4], 2)
// => [[1, 2], [3, 4]]

A size of 0 or negative returns an empty array.

chunk([1, 2, 3], 0)
// => []

View source on GitHub