Aller au contenu principal

flatMapDeep()

flatMapDeep<T>(collection, iteratee): unknown[]

Creates a flattened array of values by running each element in collection thru iteratee and recursively flattening the mapped results.

DEPRECATED

Use array.flatMap().flat(Infinity) 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.


Returns: unknown[]

The new flattened array.


See Also


Since

2.0.0


Also known as

flatMapDeep (Lodash, es-toolkit) · ❌ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Example

// ❌ Deprecated approach
flatMapDeep([1, 2], n => [[n, n]]);
// => [1, 1, 2, 2]

// ✅ Recommended approach
[1, 2].flatMap(n => [[n, n]]).flat(Infinity);
// => [1, 1, 2, 2]

How it works?

Maps and deeply flattens result. Deprecated: Use flatMap() + flat(Infinity).

Native Equivalent

// ❌ flatMapDeep(arr, fn)
// ✅ arr.flatMap(fn).flat(Infinity)

Use Cases

Map and deeply flatten 📌

Transform and flatten all nesting levels.

const data = [{ nested: [[1, 2], [3]] }, { nested: [[4]] }];
data.flatMap(d => d.nested).flat(Infinity);
// => [1, 2, 3, 4]

Extract deeply nested

Collect all values from deep structures.

const tree = [{ children: [[a], [[b, c]]] }];
tree.flatMap(n => n.children).flat(Infinity);

Flatten recursive structure

Process hierarchical data into flat list.

const items = [{ sub: [[1], [[2, 3]]] }];
items.map(i => i.sub).flat(Infinity);
// => [1, 2, 3]