flatten
Flattens nested arrays to a specified depth. Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. A depth of 1 flattens only the first level of nesting, while Infinity flattens all levels.
Installation
npx fragmen add array/flattenSource Code
/**
* Flattens nested arrays to a specified depth.
*
* Creates a new array with all sub-array elements concatenated into it recursively
* up to the specified depth. A depth of 1 flattens only the first level of nesting,
* while Infinity flattens all levels.
*
* @tags pure, array-manipulation
* @param {T[]} array The array to flatten
* @param {number} depth The maximum depth to flatten (default: 1)
* @returns {T[]} A new flattened array
*
* @example
* ```typescript
* // Single level flattening (default depth = 1)
* const nested = [1, [2, 3], [4, [5, 6]]];
* const flat = flatten(nested);
* console.log(flat); // [1, 2, 3, 4, [5, 6]]
*
* // Deep flattening
* const deepNested = [1, [2, [3, [4, 5]]]];
* const deepFlat = flatten(deepNested, Infinity);
* console.log(deepFlat); // [1, 2, 3, 4, 5]
*
* // Specific depth
* const multiLevel = [1, [2, [3, [4]]]];
* const twoLevels = flatten(multiLevel, 2);
* console.log(twoLevels); // [1, 2, 3, [4]]
*
* // Mixed data types
* const mixed = ['a', ['b', 'c'], ['d', ['e']]];
* const flatMixed = flatten(mixed);
* console.log(flatMixed); // ['a', 'b', 'c', 'd', ['e']]
* ```
*/
export function flatten<T>(array: T[], depth = 1): T[] {
// Handle edge cases
if (!Array.isArray(array)) {
return [];
}
if (depth <= 0) {
return [...array];
}
const result: T[] = [];
for (const item of array) {
if (Array.isArray(item) && depth > 0) {
result.push(...flatten(item as T[], depth - 1));
} else {
result.push(item);
}
}
return result;
}
Examples
// Single level flattening (default depth = 1)
const nested = [1, [2, 3], [4, [5, 6]]];
const flat = flatten(nested);
console.log(flat); // [1, 2, 3, 4, [5, 6]]
// Deep flattening
const deepNested = [1, [2, [3, [4, 5]]]];
const deepFlat = flatten(deepNested, Infinity);
console.log(deepFlat); // [1, 2, 3, 4, 5]
// Specific depth
const multiLevel = [1, [2, [3, [4]]]];
const twoLevels = flatten(multiLevel, 2);
console.log(twoLevels); // [1, 2, 3, [4]]
// Mixed data types
const mixed = ['a', ['b', 'c'], ['d', ['e']]];
const flatMixed = flatten(mixed);
console.log(flatMixed); // ['a', 'b', 'c', 'd', ['e']]
Related Utilities
chunk
arraySplits an array into chunks of a specified size. Creates a new array containing subarrays (chunks) of the original array, each with a maximum length of the specified size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size.
compact
arrayRemoves falsy values from an array. Creates a new array with all falsy values removed. Falsy values are: false, null, 0, "", undefined, and NaN. This is useful for cleaning arrays and ensuring only truthy values remain.
difference
arrayCreates an array of values from the first array that are not present in the other arrays. Returns a new array containing elements that exist in the first array but not in any of the subsequent arrays. The order of elements follows the order of the first array. Duplicates in the first array are preserved unless they appear in other arrays.
group-by
arrayGroups the elements of an array based on the result of a callback function. Creates an object where each key represents a group and the value is an array of items that belong to that group. The grouping is determined by the callback function which is applied to each element.
intersection
arrayFinds the intersection of two or more arrays. Returns a new array containing only the elements that are present in all provided arrays. The order of elements in the result follows the order of the first array. Duplicates are removed from the result.
sort-by
arraySorts an array of objects by a property or using a custom function. Creates a new sorted array without mutating the original. Can sort by a property name (for objects) or by using a custom iteratee function. Supports ascending and descending order.
Quick Actions
Tags
Parameters
arrayT[]The array to flatten
depthnumberThe maximum depth to flatten (default: 1)
Returns
T[]A new flattened array