Skip to content

Instantly share code, notes, and snippets.

@enricolucia
Created August 24, 2016 00:57
Show Gist options
  • Save enricolucia/def6000da98ce1e05955f56091b84f74 to your computer and use it in GitHub Desktop.
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].
/**
* 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