es-toolkit/docs/reference/array/flatten.md
2024-07-12 09:56:21 +09:00

904 B

flatten

Flattens the nested array given as an argument to the desired depth.

It works the same as Array.prototype.flat provided by default in JavaScript and returns the same type. However, its performance is superior.

Signature

function flatten<T, D extends number = 1>(arr: T[], depth?: D): Array<FlatArray<T[], D>>;

Parameters

  • arr (T[]): The array to flatten.
  • depth (D): The depth to flatten, which defaults to 1.

Returns

(Array<FlatArray<T[], D>>) A new array that has been flattened.

Examples

const array = [1, [2, 3], [4, [5, 6]]];

const result1 = flatten(array);
// Return [1, 2, 3, 4, [5, 6]]

const result2 = flatten(array, 1);
// Return [1, 2, 3, 4, [5, 6]]

const result3 = flatten(array, 2);
// Return [1, 2, 3, 4, 5, 6]