Skip to content

Instantly share code, notes, and snippets.

@ajb413
Created December 20, 2015 21:43
Show Gist options
  • Save ajb413/359e0ff320366bca0041 to your computer and use it in GitHub Desktop.
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
//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