Skip to main content

Flatten the array

You are required to implement a custom Array.prototype.flat function. This function creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Example

// Input
const arr1 = [0, 1, 2, [3, 4]];

// Output
const res = flat(arr, 1);
console.log(res); // [0, 1, 2, 3, 4]

Recursive solution

General idea:

  • Let's create a recursive function.
  • Let's write a base case for recursion: if depth is equal to 0, then just return given array
  • Iterate over a given array and on every step of iteration check whether the current item is an array or no
    • If it's an array, then flat it with the spread operator and call the recursive function with the current item
    • If it's not an array, then just push it to result array
  • Return result

Code

function flat(arr, depth = 1) {
if (depth === 0) return arr;
const result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flat(item, depth - 1));
} else {
result.push(item);
}
}

return result;
}

const test = [1, 2, [3, 4, [5, 6], 7, 8], 9];
console.log(flat(test, 2)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Time complexity: O(N)
  • Space complexity: O(N)