Created
August 24, 2016 00:57
-
-
Save enricolucia/def6000da98ce1e05955f56091b84f74 to your computer and use it in GitHub Desktop.
Function 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
/** | |
* Flattens passed in array. | |
* | |
* @param {Array} input is the array to flatten. | |
* @returns {out} returns flattened array. | |
*/ | |
function flatten(input) { | |
let i, | |
placeHolder = [input], | |
lastIndexSaved = [-1], | |
toBeout = []; | |
while (placeHolder.length) { | |
input = placeHolder.pop(); | |
i = lastIndexSaved.pop() + 1; | |
for (; i < input.length; ++i) { | |
if (Array.isArray(input[i])) { | |
placeHolder.push(input); | |
lastIndexSaved.push(i); | |
input = input[i]; | |
i = -1; | |
} else toBeout.push(input[i]); | |
} | |
} | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment