How to flatten a nested array in JS | Recursion | Javascript Interview | 1
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”.
- Amazon Front End Interview Experience and Questions
- Intuit Front End Developer Interview Questions and Experience
- Flipkart UI Engineer / Front End Interview Questions & Experience
- Walmart Front End Developer / UI Developer Interview Questions And Experience
- 100 Javascript Interview Questions To Crack Any Javascript Interview
- How To Memoize Any Function In Javascript | Memoization
- How To Scale Website | CDN | Load Balancers | Walmart Interview
- Add(1)(2)(3)…(N)() In Javascript | Sum(1,2)(3,4) | Currying
- Implement Your Own Map, Reduce, Filter Or Any New Array Method In Javascript | Prototypes
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
}
“`
felix
const flatten = (input = [])=> input.flat(Infinity);
Admin
@Anonymous Nice approach. And yes we aren't allowed to use native Array.Flat() in interviews @felix. 😛
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;
}