Skip to main content

flattenDeepThenMap

Flattens all depths of a nested array and then maps each element using the provided iteratee function.

Behaves the same as arr.flat(Infinity).map(iteratee) while improving type issues.


Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/flattenDeepThenMap1,587,624.530.0004fastest
lodash/flattenDeep.map1,222,383.950.0006-
js built-in/flat(Infinity).map330,750.780.0029slowest
  • modern-kit/flattenDeepThenMap
    • 1.30x faster than lodash/flattenDeep.map
    • 4.80x faster than js built-in/flat(Infinity).map

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 flattenDeepThenMap<T, U>(
arr: T[] | readonly T[],
iteratee: (item: ExtractNestedArrayType<T>) => U
): U[];

Usage

typescript
import { flattenDeepThenMap } from '@modern-kit/utils';

const arr = [1, 2, [3, 4, [5, 6]]];
flattenDeepThenMap(arr, (item) => ({ id: item }));
// [{ id: 1}, { id: 2}, { id: 3}, { id: 4}, { id: 5}, { id: 6}];