Last active
October 25, 2016 18:59
-
-
Save brianscroggins24/35bce24a0e3670cab150106f1b8883e5 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 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
let array = [[1,2,[3],4],[5, 6,[7]]]; | |
let newArray = flatten(array); | |
function flatten(array) { | |
if (!array || !array.length) return []; | |
let stack = [], | |
indexes = [], | |
currentIdx = 0, | |
results = []; | |
do { | |
if (!array[currentIdx]) { | |
array = stack.pop(); | |
currentIdx = indexes.pop() + 1; | |
} else if (Array.isArray(array[currentIdx])) { | |
stack.push(array); | |
indexes.push(currentIdx); | |
array = array[currentIdx]; | |
currentIdx = 0; | |
} else { | |
results.push(array[currentIdx]); | |
currentIdx++ | |
} | |
} while (array); | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment