Skip to main content

flatten()

flatten<T>(array): (T | T[])[]

Flattens array a single level deep.

DEPRECATED

Use array.flat() directly instead.

Reason:
Native equivalent method now available


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.


Parametersโ€‹

array: (T | T[])[]โ€‹

The array to flatten.


Returns: (T | T[])[]โ€‹

A new flattened array.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

flat (Remeda, Radashi) ยท flatten (Lodash, es-toolkit, Ramda, Effect) ยท flattenArrayable (Antfu) ยท โŒ (Modern Dash)


Exampleโ€‹

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

// โŒ Deprecated approach
const flattened = flatten(nested);
console.log(flattened); // [1, 2, 3, 4, [5, 6]]

// โœ… Recommended approach
const flattenedNative = nested.flat();
console.log(flattenedNative); // [1, 2, 3, 4, [5, 6]]

How it works?โ€‹

Flattens array a single level deep. Deprecated: Use array.flat() directly (ES2019).

Single Level Onlyโ€‹

Native Equivalentโ€‹

// โŒ flatten(arr)
// โœ… arr.flat()

Use Casesโ€‹

Flatten nested arrays one level ๐Ÿ“Œโ€‹

Flatten one level of nesting in arrays.

const nested = [[1, 2], [3, 4], [5]];
nested.flat();
// => [1, 2, 3, 4, 5]

Merge grouped resultsโ€‹

Combine results from grouped operations.

const grouped = [users.slice(0, 10), users.slice(10, 20)];
grouped.flat();
// => all users in single array

Normalize API responsesโ€‹

Flatten nested response structures.

const responses = [apiPage1.items, apiPage2.items];
responses.flat();