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]