Last active
October 25, 2016 14:50
-
-
Save brianscroggins24/657df693230e4e38948f126b4514c167 to your computer and use it in GitHub Desktop.
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
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
/* | |
Example of a flatten array method using recursion. If the original array is | |
large do NOT use this funtion. Too much memory is used off the stack. | |
*/ | |
let array = [[1,2,[3]],4]; | |
let newArray = flattenRecursive(array); | |
function flattenRecursive(array, results = []) { | |
for (let i = 0; i < array.length; i++) { | |
if (Array.isArray(array[i])) { | |
flattenRecursive(array[i], results); // called until the inner most array is reached | |
} else { | |
results.push(array[i]); | |
} | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment