TobilobaCodes – LeetCode Explorer

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.

πŸ’‘ 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;
}