Skip to main content

flattenDepth()

flattenDepth<T>(array, depth): T[]

Recursively flattens array up to depth times.

DEPRECATED

Use array.flat(depth) directly instead.

Reason:
Native equivalent method now available


Type Parametersโ€‹

T: Tโ€‹

The type of the leaf elements in the array.


Parametersโ€‹

array: unknown[]โ€‹

The array to flatten.

depth: number = 1โ€‹

The maximum recursion depth.


Returns: T[]โ€‹

A new flattened array.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

flattenDepth (Lodash, es-toolkit) ยท โŒ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Exampleโ€‹

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

// โŒ Deprecated approach
const flattened = flattenDepth(nested, 2);
console.log(flattened); // [1, 2, 3, [4]]

// โœ… Recommended approach
const flattenedNative = nested.flat(2);
console.log(flattenedNative); // [1, 2, 3, [4]]

How it works?โ€‹

Recursively flattens array up to specified depth. Deprecated: Use array.flat(depth) directly (ES2019).

Native Equivalentโ€‹

// โŒ flattenDepth(arr, 2)
// โœ… arr.flat(2)

Use Casesโ€‹

Flatten to specific depth ๐Ÿ“Œโ€‹

Flatten arrays to a controlled depth.

const nested = [1, [2, [3, [4]]]];
nested.flat(2);
// => [1, 2, 3, [4]]

Normalize structured dataโ€‹

Control how many levels of nesting to remove.

const data = [[a], [[b], [[c]]]];
data.flat(2);
// => [a, [b], [c]]

Process multi-level groupsโ€‹

Partially flatten grouped data.

const groups = [[[item1, item2]], [[item3]]];
groups.flat(1);
// => [[item1, item2], [item3]]