Created
November 17, 2018 20:09
-
-
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].
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
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