How to Flatten an Array in JavaScript

Rafael Thayto - Sep 20 - - Dev Community

Using recursion and a while loop is on of the easier ways to do that

export default function flatten(value) {
  const arr = []

  const flat = (a) => {
    let counter = 0
    console.log(a)
    while (counter < a.length) {
      const val = a[counter]
      if (Array.isArray(val)) {
        return flat(val)
      } else {
        arr.push(val)
      }
      counter++
    }
  }
  flat(value)
  return arr
}
Enter fullscreen mode Exit fullscreen mode

You also can do that using a reduce() and array.concat()

export default function flatten(value) {
  return value.reduce((acc, val) => 
    Array.isArray(val)
      ? acc.concat(flatten(val))
      : acc.concat(val),
  []);
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . .
Terabox Video Player