• 0

Flatten nested array javascript

Problem :

Given a nested array, flatten the given array.

Input :

[1, 2, 3, [4, 5], [6, [7, 8]]]

Output :

[1, 2, 3, 4, 5, 6, 7, 8]

Logic :

  • Iterate throgh the array
    • If the given element is an array then call the flatten function recursively
    • Else add the given element to the flattenArr, which is our resulting array

Time complexity :

O(n)

Solution :

Imperative solution



Declarative solution




Please write comments if you can make the above solution much clean, optimize or testable.