Skip to content

Instantly share code, notes, and snippets.

@brianscroggins24
Last active October 25, 2016 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brianscroggins24/35bce24a0e3670cab150106f1b8883e5 to your computer and use it in GitHub Desktop.
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].
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