Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
//once flat add the item to the array
//call the function for the first time
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
You can’t perform that action at this time.