Skip to content

Instantly share code, notes, and snippets.

@pietro909
Created February 7, 2017 10:49
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 pietro909/be871c1dd0da2415ac53ac67c9b15b56 to your computer and use it in GitHub Desktop.
Save pietro909/be871c1dd0da2415ac53ac67c9b15b56 to your computer and use it in GitHub Desktop.
A recursive flatten function for arbitrary nested arrays. Stack is the limit :-)
/**
* 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