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();