Skip to main content

flatten

Flattens a nested array to the specified depth.

JavaScript's built-in Array.prototype.flat has poor performance.

The provided flatten function outperforms both JavaScript's Array.prototype.flat and lodash's flattenDepth.


Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/flatten2,303,725.150.0004fastest
lodash/flattenDepth1,546,277.360.0006-
js built-in/flat346,378.130.0029slowest
  • modern-kit/flatten
    • 1.49x faster than lodash/flattenDepth
    • 6.65x faster than js built-in/flat

Interface

typescript
type FlatArray<Arr, Depth extends number> = {
"done": Arr,
"recur": Arr extends ReadonlyArray<infer InnerArr>
? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
: Arr
}[Depth extends -1 ? "done" : "recur"];
typescript
function flatten<T, D extends number = 1>(
arr: T[] | readonly T[],
depth?: D // default: 1
): FlatArray<T[], D>[];

Usage

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

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

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