DEV Community

[Comment from a deleted post]
Collapse
 
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
Collapse
 
ashutoshbw profile image
Ashutosh Biswas

In the recursive version, JavaScript produces SyntaxError(It would be nice if it wouldn't) cause ternary operator does not allow spreading like this. We can solve it using spread operators if we really want to, but I've found concat requires a little less typing:

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

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