Skip to content

Instantly share code, notes, and snippets.

@lucasff
Created September 18, 2019 14:54
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 lucasff/7aa85c05a1322973f5c7aa647cfadde9 to your computer and use it in GitHub Desktop.
Save lucasff/7aa85c05a1322973f5c7aa647cfadde9 to your computer and use it in GitHub Desktop.
JS flatten
const flatten = (arr, result = []) => {
if (!Array.isArray(arr)){
return [...result, arr];
}
arr.forEach((elem) => {
result = flatten(elem, result)
})
return result
}
console.log(flatten([1, [2, 3], [4, [5, 6, [7, 8]]]])) // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment