Created
March 31, 2018 17:59
-
-
Save nickihastings/2e4a9630991580ed69128c10742ec5b3 to your computer and use it in GitHub Desktop.
Flatten a nested array. You must account for varying levels of nesting.
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
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