How to flatten a nested array in JS | Recursion | Javascript Interview | 1

How to flatten a nested array? I have been asked this question number of times during my Javascript Interviews. You aren't allowed to use the inbuilt Flat() in Javascript Interviews.

How to flatten a nested array in JS | Javascript Interview

Array = [1,2,[3,4,[5,6],7],8,[9,[10,11]]]  

Required output: [1,2,3,4,5,6,7,8,9,10,11] 

We are going to write a recursive function i.e the function which calls itself to flatten a nested array

  • We are going to loop through the array and check if the item is an array
  • If it is, we are going to loop through that item by passing that to the function 
  • If it is not then we will push it to another array(blank initially)

Let's look at the code:

function Flat(myArray, newArray=[]){
 for(let i = 0; i < myArray.length; i++) { 
  // We are using isArray method of Array Prototype
   Flat(myArray[i],newArray)  // call the function again with the current array in myArray[i];
  else {  
   // if myArray[i] isn't a array, push it to new array
 return newArray

Now, this solution is intended for people with less than 1 YOE in Javascript. If you have better understanding of Javascript, you can go ahead with the below solution in order to flatten a nested array in Javascript:
function flat(myArray, newArray=[])
 myArray.forEach((item) => (Array.isArray(item))?flat(item, newArray)
 return newArray

There are several ways to flat an array in Javascript, please share your solutions in comment section. With increasing experience, you will be asked different variations of this concept. 

Please subscribe for receiving updates on my upcoming posts about interviews and JS concepts. I hope you liked my blog on "How to flatten a nested array in JS". 


  1. I like the iterating approach. i did it with a random constraint: no if statement.
    const flatten = xs => {
    const rs = []
    for (const x of xs) rs.push(...Array.isArray(x) ? flatten(x): [x])
    return rs


    1. const flatten = (input = [])=> input.flat(Infinity);

  2. @Anonymous Nice approach. And yes we aren't allowed to use native Array.Flat() in interviews @felix. 😛


Post a Comment