CyrefJS
CCyrefJS
فا
Back to documentation
Array/Since 1.38.0

chunk

Splits an array into smaller arrays of a specified size.

chunk(array, size):T[][]

Parameters

arrayT[]required

The array to split into smaller chunks.

sizenumberrequired

The maximum number of elements in each chunk.

Returns

T[][]

A new array containing the generated chunks.

Errors

Throws an error when size is less than or equal to 0.

Examples

01

Basic usage

Split an array into chunks of three elements.

TypeScript
import { chunk } from "@cyref/js";

const numbers = [1, 2, 3, 4, 5, 6, 7];

const result = chunk(numbers, 3);

console.log(result);
// [[1, 2, 3], [4, 5, 6], [7]]
02

The last chunk can be smaller

When the array length is not evenly divisible by the chunk size, the final chunk contains the remaining elements.

TypeScript
import { chunk } from "@cyref/js";

const numbers = [1, 2, 3, 4, 5, 6, 7];

const result = chunk(numbers, 3);

console.log(result);
// [[1, 2, 3], [4, 5, 6], [7]]
03

Invalid chunk size

The function throws an error when the chunk size is 0 or negative.

TypeScript
import { chunk } from "@cyref/js";

const numbers = [1, 2, 3, 4];

const result = chunk(numbers, 0);
// Error: Chunk size must be greater than 0
Built with@cyref/js·Official documentation