An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
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.
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 levelsfor (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.
Original Link: https://dev.to/dillionmegida/arrayflat-for-flatting-nested-arrays-within-an-array-3d1o
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To