DEV Community


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

edouardsouan profile image

Hello ^^. Nice use of recursion !

For the sake of discussion, here is another solution using built-in methods of Array :

const input = [1,2,3,[4,5,[6,7]],8,[9,[10,11]]]

let output = input.reduce((flattenArr, el)=>{
    flattenArr = flattenArr.concat(el.flat(2))
  return flattenArr
}, [])

Enter fullscreen mode Exit fullscreen mode

One could argue that if your input's data are nested to a higher level, you will have to adapt the flat() method accordingly, which is not an issue in your code.
But won't you be suppose to know the shape of the data you're working with ^^ ?

Thank you for your time and showing us that recursion is not terrifying !

ip127001 profile image
Rohit Kumawat Author

Thanks for reading the article and for this solution 🙌. Really appreciate it. But yeah I covered this solution because it covers recursion as well.