DEV Community

pampapati
pampapati

Posted on • Edited on

Flat Nested Array: JavaScript

Flat nested array without using built-in methods. Recursive program example

const arr = [1,2,[3,4],5,[6,[7,8],9],10];

function flatArray(input,output){   
  input.forEach( (value)=>{    
    if(typeof value== 'object'){
      flatArray(value,output);
    }else{
      output.push(value);
    }    
  });
  return output;  
}

console.log(flatArray(arr,[]));
Enter fullscreen mode Exit fullscreen mode

Top comments (5)

Collapse
 
jonrandy profile image
Jon Randy 🎖️
console.log(arr.flat(Infinity))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pampapati profile image
pampapati • Edited

This is sample example,not using built in methods. Way to learn coding :)

Collapse
 
ajstacy profile image
Andrew Stacy

Nice recursive code! As a side-note, this is built into the JS standard:

developer.mozilla.org/en-US/docs/W...

Collapse
 
decker67 profile image
decker • Edited

Why creating a local?
Also interesting name xValue?
I once had a college who named all his variables x1, x2, ....

Collapse
 
pampapati profile image
pampapati • Edited

Cleaned up the code . Thanks for the feedback :)