flatMapDeep
Applies an iteratee function to each element of the array and flattens the result to all depths.
Behaves the same as arr.map.flat(Infinity) but with better performance.
Code
Benchmark
hz: Operations per secondmean: Average response time (ms)
| Name | hz | mean | Performance |
|---|---|---|---|
| modern-kit/flatMapDeep | 251,685.91 | 0.0040 | fastest |
| lodash/flatMapDeep.map | 184,467.29 | 0.0054 | - |
| js built-in/map.flat | 57,011.35 | 0.0175 | slowest |
- modern-kit/flatMapDeep
1.35xfaster than lodash/flatMapDeep.map4.41xfaster than js built-in/map.flat
Interface
typescript
/**
* @description A utility type that recursively unwraps nested array types to extract the innermost element type
*/
type ExtractNestedArrayType<T> = T extends readonly (infer U)[]
? ExtractNestedArrayType<U>
: T;
typescript
function flatMapDeep<T, U>(
arr: T[] | readonly T[],
iteratee: (item: ExtractNestedArrayType<T>) => U
): U[];
Usage
typescript
import { flatMapDeep } from '@modern-kit/utils';
const arr = [1, 2, [3, 4, [5, 6]]];
flatMapDeep(arr, (item) => ({ id: item }));
// [{ id: 1}, { id: 2}, { id: 3}, { id: 4}, { id: 5}, { id: 6}];