JavaScript interview questions – Flatten an array in JavaScript

This is also one of the most common questions you will find in your JavaScript or FrontEnd interview questions. The idea here is very simple, you are given an array which can contain a variable or an array in itself and output we want is a flattened array which has just values and no nested array in itself.

For example – 

Input – [ 2, 3 , [ 4, 5, 6, [ 7 ], 8 ], 9]  Output – [ 2, 3, 4, 5, 6, 7, 8, 9 ]

Input  – [ 2, 3, 4, 5, [6] ]   Output – [ 2, 3, 4, 5, 6 ]

Code – 

Concept here is very simple, in our flattenArray function we will iterate through each item in an array and check if it is an array using native Array.isArray function.

  • If item is an array, we will iteratively call flattenArray function and concat it to to results
  • If item is not an array we will push item in the results array

 

 

Leave a Reply

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