Skip to content

Instantly share code, notes, and snippets.

@adaam2
Last active April 14, 2016 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adaam2/ad7d8b2bc3a8e8ee8452b3e0ef8be253 to your computer and use it in GitHub Desktop.
Save adaam2/ad7d8b2bc3a8e8ee8452b3e0ef8be253 to your computer and use it in GitHub Desktop.
Flattening arrays (https://jsfiddle.net/vj6jvaxu/)
var arr = [[1,2,[3]],4];
// Call the method
var flattened = flatten(arr);
// Print the result out to the console..
console.log(flattened);
function flatten(arr) {
var flatArray = [];
for(var i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i])) {
// call this function recursively
var recursivelyFlattenedArray = flatten(arr[i]);
flatArray = flatArray.concat(recursivelyFlattenedArray);
}
else
{
// Otherwise just add it to the main return value array!
flatArray.push(arr[i]);
}
}
// Return to the caller!
return flatArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment