DEV Community

Rafael Thayto
Rafael Thayto

Posted on

How to Flatten an Array in JavaScript

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

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Why not just use the built-in Array.prototype.flat? It's faster, and has the option of flattening n levels

Collapse
 
thayto profile image
Rafael Thayto

I posted this, because sometimes people need to know how to do it manually on code challenges :)