For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/array/flatten.md.

flatten es-toolkit

Returns a new array that is flattened to the specified depth.

const result = flatten(arr, depth);

Usage

flatten(arr, depth = 1)

Use flatten when you want to flatten a nested array to a specific depth. It unwinds arrays within arrays to the specified level, creating a flatter structure.

It works identically to the Array#flat included in the JavaScript language, but it's faster.

import { flatten } from 'es-toolkit/array';

// Flatten with default depth of 1
const array = [1, [2, 3], [4, [5, 6]]];
flatten(array);
// Returns: [1, 2, 3, 4, [5, 6]]

// Flatten with depth of 2
flatten(array, 2);
// Returns: [1, 2, 3, 4, 5, 6]

You can control the depth to flatten only to the desired level.

import { flatten } from 'es-toolkit/array';

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

// Flatten with depth of 1 (default)
const result1 = flatten(array, 1);
// Returns: [1, 2, 3, 4, [5, 6]]

// Flatten with depth of 2
const result2 = flatten(array, 2);
// Returns: [1, 2, 3, 4, 5, 6]

Parameters

arrT[]required

The nested array to flatten.

depthDoptional

The depth to flatten. Defaults to 1.

Returns

Returns a new array flattened to the specified depth.

Array<FlatArray<T[], D>>
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.