Skip to content

Instantly share code, notes, and snippets.

@ulisesbocchio
Created March 1, 2018 06:46
Show Gist options
  • Save ulisesbocchio/bad96e91f7ee50e1bfa1deeec2daab77 to your computer and use it in GitHub Desktop.
Save ulisesbocchio/bad96e91f7ee50e1bfa1deeec2daab77 to your computer and use it in GitHub Desktop.
ES6 flatten
export default function flatten(arrOrElem) {
return Array.isArray(arrOrElem) ? arrOrElem.reduce((flat, elem) => ([...flat, ...flatten(elem)]), []) : [arrOrElem];
}
@ulisesbocchio
Copy link
Author

Limitations:

  • Spatial complexity: Creates a bunch of intermediate arrays
  • Computational complexity: O(n) where n = total number of elements
  • Can only flatten as many levels as stack calls allowed due to recursive nature

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment