DEV Community

[Comment from a deleted post]
Collapse
 
edouardsouan profile image
RWRFyZA

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)=>{
  if(Array.isArray(el)){
    flattenArr = flattenArr.concat(el.flat(2))
  }else{
    flattenArr.push(el)
  }
  return flattenArr
}, [])

console.log(output)
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 !

Collapse
 
ip127001 profile image
Rohit Kumawat

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