Created
January 12, 2016 23:05
-
-
Save fanaugen/4f6f5f1871c0ad160db3 to your computer and use it in GitHub Desktop.
recursive function to flatten a js Array
This file contains hidden or 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 steamroller(arr) { | |
for (var i = 0; i < arr.length; i++) { | |
if(Array.isArray(arr[i])) { | |
// recurse: replace this array with all its elements | |
// for instance, if arr is [1, [2, 3], 4] | |
// then we want to return [1, 2, 3, 4] | |
var left = arr.slice(0, i); | |
var right = arr.slice(i + 1); | |
return steamroller( | |
left.concat( arr[i] ).concat(right) | |
); | |
} | |
} | |
// base case: we haven’t returned until this point, which | |
// means that none of the elements of arr are arrays, so | |
// arr is flat. | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
passes all tests on http://www.freecodecamp.com/challenges/bonfire-steamroller