Array.flat() - for flatting nested arrays within an array
Dillion Megida
Posted on April 12, 2022
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]]]
[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)
The depth
argument specifies the nest level you want to concatenate. Using this example:
[1, 2, [3, 4, [5, 6]]]
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 ]
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 ]
Browser Support
The flat
method was introduced in ES2019 and currently, the browser support gotten from MDN is displayed here:
Pretty good.
Posted on April 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.