Last active
September 26, 2016 10:44
-
-
Save siddharthpolisiti/f70ccf3ca9c55f32a00f5aeb0650e3a7 to your computer and use it in GitHub Desktop.
This program converts nested arrays to flat array structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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