#2625
Medium JavaScript Flatten deeply nested array
65.5% acceptance
Mar 2, 2026
423
32
Given a multi-dimensional array arr and a depth n, return a flattened version of that array.
A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
A flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n. The depth of the elements in the first array are considered to be 0.
Please solve it without the built-in Array.flat method.
Solution
TypeScript
Time O(n)
Space O(1)
type MultiDimensionalArray = (number | MultiDimensionalArray)[];
var flat = function (
arr: MultiDimensionalArray,
n: number,
): MultiDimensionalArray {
if (n === 0) return arr;
const result: MultiDimensionalArray = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flat(item as MultiDimensionalArray, n - 1));
} else {
result.push(item);
}
}
return result;
};