Skip to main content

Command Palette

Search for a command to run...

Array.flat()

Published
1 min readView as Markdown
const array = [1, [2, [3, 4, [5, 6]]], 7];

console.log(array.flat(1)); // [ 1, 2, [ 3, 4, [ 5, 6 ] ], 7 ]
console.log(array.flat(2)); // [ 1, 2, 3, 4, [ 5, 6 ], 7 ]
console.log(array.flat(3)); // [ 1, 2, 3, 4, 5, 6, 7 ]

.flat() (ES2019) will flatten an array up to the given depth level.

P

ES2019 introduced the Array.prototype.flat() method that creates a new array with all the elements of the subarrays concatenated to it recursively up to a specified depth.

The following shows the syntax of the flat() method:

let newArray = arrayObject.flat([depth])
let arr = [[1, 2],[3, 4, [5, 6 [7, 8], 9]],[10 [11, 12]]];

// since the default depth is 1
// only the first level arrays in the parent array are flattend
// you would notice that there's a second level nesting after the number '4', in the parent array

arr.flat();
// [ 1, 2, 3, 4, [ 5, 6, [ 7, 8 ], 9 ], 10, [ 11, 12 ] ]


// we supplied 2 as the depth

arr.flat(2);
// [ 1, 2, 3, 4, 5, 6, [ 7, 8 ], 9, 10, 11, 12 ]


// using 'Infinty' as an argument means flatten all levels to a one-dimensional array

arr.flat(Infinity);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

// the flat() method also remove empty slots in the array, otherwise called 'array holes'
let arrrayHole = [1, 2, , 4, 5];
arrayHole.flat();
// [1, 2, 4, 5]
A
console.log(array.flat(Infinity));

will flat an array any level deep

1

More from this blog

Codedrops.tech

49 posts