Skip to content

chunk ​

Splits an array into smaller arrays of a specified size.

typescript
const chunked = chunk(arr, size);

Usage ​

chunk(arr, size) ​

Use chunk when you want to split a long array into multiple smaller arrays of the same size. If the array cannot be evenly divided, the last chunk will contain the remaining elements.

typescript
import { chunk } from 'es-toolkit/array';

// Split a number array into chunks of size 2.
chunk([1, 2, 3, 4, 5], 2);
// Returns: [[1, 2], [3, 4], [5]]

// Split a string array into chunks of size 3.
chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
// Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Splitting an empty array returns an empty array.

typescript
import { chunk } from 'es-toolkit/array';

chunk([], 2); // []

Parameters ​

  • arr (T[]): The array to split.
  • size (number): The size of each chunk. Must be a positive integer.

Returns ​

(T[][]): A 2D array split into chunks of size size.

Throws ​

Throws an error if size is not a positive integer.

Try It ​

import "./styles.css";

document.getElementById("app").innerHTML = `
<h1>Hello world</h1>
`;

Released under the MIT License.