Created
February 7, 2017 10:49
-
-
Save pietro909/be871c1dd0da2415ac53ac67c9b15b56 to your computer and use it in GitHub Desktop.
A recursive flatten function for arbitrary nested arrays. Stack is the limit :-)
This file contains hidden or 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 arbitrary nested arrays. | |
* | |
* @arg the array to flatten | |
* @return array with depth 1, empty array for non-arrays | |
*/ | |
const flatten = (arrayOfArrays = []) => { | |
if (arrayOfArrays.length === 0) { | |
return [] | |
} | |
const head = arrayOfArrays[0] | |
const tail = flatten(arrayOfArrays.slice(1)) | |
if (Array.isArray(head)) { | |
if (head.length > 0) { | |
return [...flatten(head), ...tail] | |
} else { | |
return tail | |
} | |
} else { | |
return [head, ...tail] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment