Flatten a nested array

Problem Statement: Given a multi-dimensional array arr, return a flattened version of that array.

Read:

  • multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
  • flattened array is a version of the original array with all of the sub-arrays removed and replaced with the actual elements in that sub-array.

Input/Output:

  • Input: [1, 2, [3, 4, [5, 6, 7, [8, 9, 10, [11, 12, [13, 14]]]]]]
  • Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];

Solution:

function flattenArray(arr) {
    let res = [];
    
    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            res = res.concat(flattenArray(arr[i]));
        } else {
            res.push(arr[i]);
        }
    }
    
    return res;
}

let array = [1,2,[3,4,[5,6,7,[8,9,10,[11,12,[13,14]]]]]];
console.log(flattenArray(array));  // Output: [1,2,3,4,5,6,7,8,9,10,11,12,13,14]