Skip to content

Instantly share code, notes, and snippets.

@siddharthpolisiti
Last active September 26, 2016 10:44
Show Gist options
  • Save siddharthpolisiti/f70ccf3ca9c55f32a00f5aeb0650e3a7 to your computer and use it in GitHub Desktop.
Save siddharthpolisiti/f70ccf3ca9c55f32a00f5aeb0650e3a7 to your computer and use it in GitHub Desktop.
This program converts nested arrays to flat array structure
// JSBIN link - http://jsbin.com/wedoqeyezi/edit?js,output (EDIT - http://jsbin.com/kuvepo/edit?js,console)
// The below works because the first iteration find this elements and checks whether they are array or not if not then it simply
// pushes the element to the flatArray else if they are array they are sent to recursive function for further processing till a
// value(not array) is reached and then finally pushed to flatArray.
var arr = [[1,2,[3]],4];
flatArray = [];
for(var i=0;i<arr.length;i++){
if(arr[i].length === undefined){
flatArray.push(arr[i]);
}
else{
recursive(arr[i]);
}
}
function recursive(arrRec){
for(var j=0;j<arrRec.length;j++){
if(arrRec[j].length === undefined){
flatArray.push(arrRec[j]);
}
else{
recursive(arrRec[j]);
}
}
}
console.log(arr);
console.log(flatArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment