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