Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Contact us
Hide Buttons

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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *