Skip to content

chunkArray()

chunkArray<T>(array, size): T[][]

Defined in: src/utils/arrayUtils.ts:21

Chunks an array into smaller arrays of a specified size.

If the size is invalid (e.g., non-positive integer), the entire array will be returned as a single chunk.

Type Parameters

T

The type of elements in the array.

Parameters

array

T[]

The array to divide into chunks.

size

number

The size of each chunk. Must be a positive integer.

Returns

T[][]

A two-dimensional array where each inner array is a chunk of the specified size.

Example

typescript
const data = [1, 2, 3, 4, 5, 6];
const chunks = chunkArray(data, 2);
console.log(chunks); // [[1, 2], [3, 4], [5, 6]]

const invalidChunks = chunkArray(data, -1);
console.log(invalidChunks); // [[1, 2, 3, 4, 5, 6]]

Released under the MIT License.