How to flatten an Array with nested arrays

Posted on October 9, 2021

Suppose this array:

const source = ['This is a string', 1, 2, [3], [4, [5, 6]], [[7]], 8, '[10, 11]']

And want to get:

 // ["This is a string", 1, 2, 3, 4, 5, 6, 7, 8, "[10, 11]"

You can use this function:

function flatten (hold, arr) {
  arr.forEach(d => {
    if (Array.isArray(d)) {
      flatten(hold, d)
    } else {
      hold.push(d)
    }
  })
}

In this way:

const res = []
flatten(res, source)