flattenDeep()
flattenDeep<
T>(array):T[]
Recursively flattens array.
DEPRECATED
Use array.flat(Infinity) 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.
Returns: T[]
A new deeply flattened array.
See Also
Since
2.0.0
Also known as
flat (Radashi) · flatten (Ramda) · flattenDeep (Lodash, es-toolkit, Remeda) · ❌ (Effect, Modern Dash, Antfu)
Example
const deeplyNested = [1, [2, [3, [4, [5]]]]];
// ❌ Deprecated approach
const flattened = flattenDeep(deeplyNested);
console.log(flattened); // [1, 2, 3, 4, 5]
// ✅ Recommended approach
const flattenedNative = deeplyNested.flat(Infinity);
console.log(flattenedNative); // [1, 2, 3, 4, 5]
How it works?
Recursively flattens an array to a single level.
Deprecated: Use array.flat(Infinity) directly.
Deep Recursion
Native Equivalent
// ❌ flattenDeep(arr)
// ✅ arr.flat(Infinity)
Use Cases
Flatten deeply nested structures 📌
Flatten all levels of nesting in arrays.
const nested = [1, [2, [3, [4, [5]]]]];
nested.flat(Infinity);
// => [1, 2, 3, 4, 5]
Normalize tree data
Extract all items from a tree structure.
const tree = [node1, [node2, [node3, node4]]];
tree.flat(Infinity);
// => [node1, node2, node3, node4]
Collect all leaf values
Get all leaf values from nested data.
const data = [[a, [b, c]], [[d], e]];
data.flat(Infinity);
// => [a, b, c, d, e]