Skip to main content

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

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/flatMapDeep251,685.910.0040fastest
lodash/flatMapDeep.map184,467.290.0054-
js built-in/map.flat57,011.350.0175slowest
  • modern-kit/flatMapDeep
    • 1.35x faster than lodash/flatMapDeep.map
    • 4.41x faster 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}];