flatten
The flatten utility recursively flattens nested arrays into a single-level array. It can handle arbitrarily deep nesting.
Implementation
View Source Code
ts
type FlatArray<T> = T extends readonly (infer U)[] ? U : T;
/**
* Flattens a nested array into a single-level array.
*
* @example
* ```ts
* const arr = [1, [2, [3, [4, [5]]]]];
* flatten(arr) // [1, 2, 3, 4, 5];
* ```
*
* @param array - The array to flatten.
*
* @returns A single-level array.
*/
export function flatten<T>(array: T[]): FlatArray<T>[] {
return array.flat(Number.POSITIVE_INFINITY) as FlatArray<T>[];
}Features
- Isomorphic: Works in both Browser and Node.js.
- Deep Flattening: Recursively flattens arrays of any depth.
- Type-safe: Properly handles type inference for the flattened result.
API
ts
function flatten<T>(array: any[]): T[];Parameters
array: The array to flatten. Can contain primitives, objects, or other arrays.
Returns
- A new, single-level array containing all non-array elements from the input.
Examples
Flattening Multiple Levels
ts
import { flatten } from '@vielzeug/toolkit';
const nested = [1, [2, [3, [4, [5]]]]];
const flat = flatten(nested);
// [1, 2, 3, 4, 5]Normalizing Data
ts
import { flatten } from '@vielzeug/toolkit';
const matrix = [
[1, 2],
[3, 4],
[5, 6],
];
flatten(matrix);
// [1, 2, 3, 4, 5, 6]Implementation Notes
- Internally uses recursion or
Array.prototype.flat(Infinity)where supported. - Throws
TypeErrorif the first argument is not an array. - Empty arrays within the nesting are removed (as they contain no elements to flatten).