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