Skip to main content

flattenDeep

A function based on flatten that flattens all depths of a given nested array.

Compared to JavaScript's built-in Array.prototype.flat(Infinity), it offers superior performance and more accurate type inference.

typescript
// as-is
// Array.prototype.flat(Infinity)
const arr = [1, [2, [3]]].flat(Infinity);
/*
* const arr: FlatArray<number | (number | number[])[], 0 | 1 | 2 | 3 | -1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20>[]
*/
typescript
// to-be
// flattenDeep
const arr = flattenDeep([1, [2, [3]]]);
/*
* const arr: number[]
*/

Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/flattenDeep2,028,846.090.0005fastest
lodash/flattenDeep1,481,161.980.0007-
js built-in/flat(Infinity)340,193.060.0029slowest
  • modern-kit/flattenDeep
    • 1.40x faster than lodash/flattenDeep
    • 5.99x faster than js built-in/flat(Infinity)

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 flattenDeep<T>(arr: T[] | readonly T[]): ExtractNestedArrayType<T>[]

Usage

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

const arr = [1, [2, [3, [4, [5]]]]];

flattenDeep(arr); // [1, 2, 3, 4, 5]