Skip to content

Instantly share code, notes, and snippets.

@medaminefh
Created September 5, 2021 13:35
Show Gist options
  • Save medaminefh/ba0b18be3dd519dfa6b0a96bf8cf7be1 to your computer and use it in GitHub Desktop.
Save medaminefh/ba0b18be3dd519dfa6b0a96bf8cf7be1 to your computer and use it in GitHub Desktop.
create a one-dimensional array from a multidimensional array in Javascript
['Dog', ['Sheep', 'Wolf']].flat()
//[ 'Dog', 'Sheep', 'Wolf' ]
/*By default it only "flats" up to one level, but you can add a parameter to set the number of
levels you want to flat the array to. Set it to
Infinity
to have unlimited levels:
*/
['Dog', ['Sheep', ['Wolf']]].flat()
//[ 'Dog', 'Sheep', [ 'Wolf' ] ]
['Dog', ['Sheep', ['Wolf']]].flat(2)
//[ 'Dog', 'Sheep', 'Wolf' ]
['Dog', ['Sheep', ['Wolf']]].flat(Infinity)
//[ 'Dog', 'Sheep', 'Wolf' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment