Flatten Array

This problem will allow us to perform a task that has practical uses in a developer's career. We'll discuss how to flatten deeply nested arrays and why a recursive solution is a good way to attack this problem.

Flatten Array


Write a function that will take an array of deeply nested arrays and extract every item, flattening the array. It should return a new array that contains the items of each internal array, preserving order.

Input: Array

Output: Array


flatten([ [ [ [1], 2], 3], [4], [], [[5]]]);
// -> [1, 2, 3, 4, 5]

flatten(['abc', ['def', ['ghi', ['jkl']]]]);
// -> ['abc', 'def', 'ghi', 'jkl']


  • As in the last problem, we have to process every item we receive. There’s no way to get around that so the best time complexity we can hope for is O(n).

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.