flatMapDepth()
flatMapDepth<
T>(collection,iteratee,depth):unknown[]
Creates a flattened array of values by running each element in collection thru iteratee and flattening the mapped results up to depth times.
DEPRECATED
Use array.flatMap().flat(depth) directly instead.
Type Parametersโ
T: Tโ
The type of elements in the collection.
Parametersโ
collection: readonly T[]โ
The collection to iterate over.
iteratee: (value, index, collection) => unknownโ
The function invoked per iteration.
depth: number = 1โ
The maximum recursion depth. Defaults to 1.
Returns: unknown[]โ
The new flattened array.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
flatMapDepth (Lodash, es-toolkit) ยท โ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)
Exampleโ
// โ Deprecated approach
flatMapDepth([1, 2], n => [[[n, n]]], 2);
// => [[1, 1], [2, 2]]
// โ
Recommended approach
[1, 2].flatMap(n => [[[n, n]]]).flat(2);
// => [[1, 1], [2, 2]]
How it works?โ
Maps and flattens result to specified depth.
Deprecated: Use flatMap() + flat(depth).
Native Equivalentโ
// โ flatMapDepth(arr, fn, depth)
// โ
arr.flatMap(fn).flat(depth - 1)
Use Casesโ
Map and flatten to depth ๐โ
Transform and flatten to a specific depth.
const data = [{ items: [["a"], ["b"]] }];
data.flatMap(d => d.items).flat(1);
// => ["a", "b"]
Control flattening levelโ
Flatten only a certain number of levels.
const nested = [[[[1]], [[2]]]];
nested.flat(2);
// => [[1], [2]]
Partial flattenโ
Keep some nesting while flattening others.
const groups = [[[a, b]], [[c, d]]];
groups.flat(1);
// => [[a, b], [c, d]]