2625. Flatten Deeply Nested Array
Given a multi-dimensional array arr and a depth n, return a version of the array flattened to that depth. Do not use Array.prototype.flat().
π Problem Statement
A multi-dimensional array contains integers or other nested arrays. Flattening means replacing those nested arrays with their elements.
- Flatten only up to the given depth
n. - The initial array has depth 0. Nested elements increase in depth as you go deeper.
- You must not use the built-in
flat()method.
π‘ Example
arr = [1, [2, [3, [4]], 5]]
n = 1
// β [1, 2, [3, [4]], 5]
n = 2
// β [1, 2, 3, [4], 5]
n = 3
// β [1, 2, 3, 4, 5]
π§ Explanation
Recursively loop through the array. For each element:
- If itβs an array and depth is not yet exhausted, flatten it one level deeper.
- Otherwise, push it to the result as-is.
Keep track of the current depth and stop when it equals the specified limit.
β Your Solution
/**
* @param {Array} arr
* @param {number} depth
* @return {Array}
*/
function flat(arr, depth) {
const result = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
result.push(...flat(item, depth - 1));
} else {
result.push(item);
}
}
return result;
}