DEV Community

pampapati
pampapati

Posted on • Updated 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

Latest comments (5)

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 :)

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 :)