Aller au contenu principal

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]]