Back to Snippets
CODE
Array Flattening (Specified Depth)
Description
Flattens nested arrays with configurable depth, perfect for processing multi-level nested data structures
Code
/**
* Array flattening with configurable depth
* @param arr Array to be flattened
* @param depth Flattening depth (Infinity by default)
* @returns Flattened array
*/
function flattenArray<T>(arr: any[], depth = Infinity): T[] {
return arr.reduce((acc, item) => {
if (Array.isArray(item) && depth > 0) {
acc.push(...flattenArray(item, depth - 1));
} else {
acc.push(item);
}
return acc;
}, [] as T[]);
}
// Usage Example
console.log(flattenArray([1, [2, [3, [4]]]], 2)); // [1, 2, 3, [4]]
console.log(flattenArray([1, [2, [3]]])); // [1, 2, 3]Usage
Great for processing nested API responses, tree-structured data, or multi-level menu arrays