Skip to main content

Built and signed on GitHub Actions

A modern JavaScript utility library that's 2-3 times faster and up to 97% smaller—a major upgrade to lodash.

This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
94%
Published
a day ago (1.12.0)
function chunk
chunk<T>(
arr: readonly T[],
size: number,
): T[][]

Splits an array into smaller arrays of a specified length.

This function takes an input array and divides it into multiple smaller arrays, each of a specified length. If the input array cannot be evenly divided, the final sub-array will contain the remaining elements.

Examples

Example 1

// Splits an array of numbers into sub-arrays of length 2 chunk([1, 2, 3, 4, 5], 2); // Returns: [[1, 2], [3, 4], [5]]

Example 2

// Splits an array of strings into sub-arrays of length 3 chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3); // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Type Parameters

The type of elements in the array.

Parameters

arr: readonly T[]
  • The array to be chunked into smaller arrays.
size: number
  • The size of each smaller array. Must be a positive integer.

Return Type

T[][]

A two-dimensional array where each sub-array has a maximum length of size.

Add Package

deno add @es-toolkit/es-toolkit

Import symbol

import { chunk } from "@es-toolkit/es-toolkit";

Add Package

npx jsr add @es-toolkit/es-toolkit

Import symbol

import { chunk } from "@es-toolkit/es-toolkit";

Add Package

yarn dlx jsr add @es-toolkit/es-toolkit

Import symbol

import { chunk } from "@es-toolkit/es-toolkit";

Add Package

pnpm dlx jsr add @es-toolkit/es-toolkit

Import symbol

import { chunk } from "@es-toolkit/es-toolkit";

Add Package

bunx jsr add @es-toolkit/es-toolkit

Import symbol

import { chunk } from "@es-toolkit/es-toolkit";