Javascript Concepts

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++) {
if(Array.isArray(myArray[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 {
newArray.push(myArray[i])
// 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)
:newArray.push(item))
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”. 




4 Comments

  • Anonymous

    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
    }
    “`

  • Mohit Kumar

    Array.prototype.myFlat = function fn(){
    let newArr = [];
    for(let val of this){
    if(typeof val === ‘object’) newArr=newArr.concat(fn.apply(val,null)) //fn.call(val,null) will also work. we need ‘this’ to be handled in for loop so bind is necessary
    else newArr.push(val)
    }
    return newArr;
    }

Leave a Reply

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

Subscribe to receive helpful content for your next Front End Interview. No Junk. No Spam.

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

FE / JS will use the information you provide on this form to be in touch with you and to provide updates and marketing.