Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 31, 2018 17:59
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 nickihastings/2e4a9630991580ed69128c10742ec5b3 to your computer and use it in GitHub Desktop.
Save nickihastings/2e4a9630991580ed69128c10742ec5b3 to your computer and use it in GitHub Desktop.
Flatten a nested array. You must account for varying levels of nesting.
function steamrollArray(arr) {
// I'm a steamroller, baby
var result = []; //store the resulting flat array
//function to recursively flatten arrays inside of arrays.
function flatten(arr){
//for every item in the array check if it is an array itself
for(var i = 0; i < arr.length; i++){
if(Array.isArray(arr[i]) ){
//if it is an array call the flatten function and concatinate the results
//this will be called on all multidimensional arrays until flat
result.concat(flatten(arr[i]));
}
else{
//once flat add the item to the array
result.push(arr[i]);
}
}
}
//call the function for the first time
flatten(arr);
return result;
}
steamrollArray([1, [2], [3, [[4]]]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment