DEV Community


Discussion on: How to flatten an array using recursion in Javascript

patarapolw profile image
Pacharapol Withayasakpunt
  • Why would you have unstructured data required to be flattened like that in the first place?
  • Classical solution for this would be using .reduce or an equivalent.
const flatten = (arr) => arr.reduce((prev, c) => [...prev, ...c], [])
Enter fullscreen mode Exit fullscreen mode

Then, for a more complex version.

const flatten = (arr) => arr.reduce((prev, c) => [...prev, Array.isArray(c) ? ...flatten(c) : c], [])
Enter fullscreen mode Exit fullscreen mode
ip127001 profile image
Rohit Kumawat Author

Thanks for reading the post and for another solution. I just wanted to cover use cases of recursion.