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]