Created
December 20, 2015 21:43
-
-
Save ajb413/359e0ff320366bca0041 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
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
//Set the array of arbitrarily nested arrays to startArray | |
//The flattened array is stored in endArray after flatten(startArray) is executed | |
var startArray = [[1,2,[3]],4]; | |
var endArray = new Array(); | |
flatten(startArray); | |
console.log('original: ' + startArray); | |
console.log('flattened: ' + endArray); | |
function flatten(input, output) | |
{ | |
for (var i = 0; i < input.length; i++) | |
{ | |
if (typeof(input[i]) === "object") | |
{ | |
flatten(input[i]); | |
} | |
else | |
{ | |
endArray.push(input[i]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment