DEV Community

Cover image for Array.flat() - for flatting nested arrays within an array
Dillion Megida
Dillion Megida

Posted on • Edited on

Array.flat() - for flatting nested arrays within an array

In this third article of the Array method series, I'll explain the flat method and how it works.

Here's the video version: Array.flat() YouTube

What is the Flat Method?

The flat method of arrays is used to flatten nested arrays within an array. What are nested arrays?

const array = [1, 2, [3, 4, [5, 6]]]
Enter fullscreen mode Exit fullscreen mode

[3, 4, [5, 6]] is nested within the main array, and [5,6] is also nested in the previous array.

With the flat method, you can concatenate these nested arrays to the parent array.

The returned output of the flat method is a new array containing the concatenated items.

Syntax of the Flat method

array.flat(depth)
Enter fullscreen mode Exit fullscreen mode

The depth argument specifies the nest level you want to concatenate. Using this example:

[1, 2, [3, 4, [5, 6]]]
Enter fullscreen mode Exit fullscreen mode

Depth 1 - [3, 4, [5, 6]
Depth 2 - [5, 6]
Depth 3 - There's no third depth

You can also pass a depth of Infinity, which goes deeper to unnest the deepest nested array 🔥 haha.

Without the Flat method

Here's how to flatten an array without the Flat method:

const array = [1, 2, [3, 4, [5, 6]]]
const flattenedArr = []

// for 2 levels
for (let i = 0; i < array.length; i++) {
  const item = array[i]

  if (!Array.isArray(item)) {
    // not an array
    flattenedArr.push(item)
  } else {
    // for the first level
    for (let j = 0; j < item.length; j++) {
      const item2 = item[j]

      if (!Array.isArray(item2)) {
        // not an array
        flattenedArr.push(item2)
      } else {
        // for the second level
        flattenedArr.push(...item2)
      }
    }
  }
}

console.log(flattenedArr)
// [ 1, 2, 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

Looping and looping, just to flatten an array. The flat method is definitely a lifesaver 😅

NB: This is not the only way to do it without the flat method. Check out more ways in this StackOverflow discussion

With the Flat method

const array = [1, 2, [3, 4, [5, 6]]]
const flattenedArr = array.flat(2)
// or array.flat(Infinity)

console.log(flattenedArr)
// [ 1, 2, 3, 4, 5, 6 ]
Enter fullscreen mode Exit fullscreen mode

Browser Support

The flat method was introduced in ES2019 and currently, the browser support gotten from MDN is displayed here:

Browser support for the Flat Method gotten from MDN

Pretty good.

Top comments (2)

Collapse
 
tanth1993 profile image
tanth1993

thank you, new method in array for me

Collapse
 
dillionmegida profile image
Dillion Megida

Glad you found it helpful :)