Aller au contenu principal

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