Skip to content

Flatten Deeply Nested Array – 2625

🔗LC2625 🟡 Medium 🧩 Pattern – JSON, Arrays and Objects

📅 Day 26/30 Days of JavaScript

Given a multidimensional array arr and a depth n, return a flattened version of that array.

A multidimensional array is a recursive data structure that contains integers or other multidimensional arrays.

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.

Example

Input
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 0
Output
[1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]

Input
arr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 1
Output
[1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15]

Input
arr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]
n = 2
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]Code language: JavaScript (javascript)

Solution

/**
 * @param {Array} arr
 * @param {number} depth
 * @return {Array}
 */
var flat = function (arr, n) {
    const result = [];
    arr.forEach(item => {
        if (Array.isArray(item) && n > 0) {
            // Iterate one more level deep with recursion
            result.push(...flat(item, n - 1));
        } else {
            result.push(item);
        }
    })
    return result;
};Code language: JavaScript (javascript)
Back to Top