Skip to content

Instantly share code, notes, and snippets.

@ForkInSpace
Created November 17, 2018 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ForkInSpace/ee06ed9d3531ebd12e12e2dd96e80914 to your computer and use it in GitHub Desktop.
Save ForkInSpace/ee06ed9d3531ebd12e12e2dd96e80914 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].
flatten = (array, result) => {
if(array.length === 0) return result;
let head = array[0];
let rest = array.slice(1);
if (Array.isArray(head)) {
return flatten(head.concat(rest), result);
};
result.push(head);
return flatten(rest, result);
};
console.log(flatten([[1,2,[3]], 4], [])); // [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment