Array.flat() in javascript

In this blog you will learn about Array.flat() or Array.prototype.flat() function.

Introduction

Array.prototype.flat() function introduced with ES2019. which you could use to flatten the arrays. This function actually creates a brand new array with all the sub-array elements concatenated into it recursively up to the specified depth.

Syntax

arrayObject.flat([depth])

Here depth is the optional parameter. default value for the depth is 1

Example

//Suppose we have array object as follows
var arr = [1,2,3,4,[5,6,7,8,[9,10,11,12]]]

//Using flat
var result = arr.flat()
console.log(result)

Output

[1, 2, 3, 4, 5, 6, 7, 8, Array(4)]

In the above example we didn't pass depth argument so by default depth value is 1. So the first nested array is concatenated into the main array. if we want to concatenated [9,10,11,12] as well then we have to use flat() function one more time or otherwise we have to pass the depth argument. like as follows.

Flatten the array without passing depth

var arr = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]]

arr.flat() //[1, 2, 3, 4, 5, 6, Array(4)]

arr.flat().flat() //[1, 2, 3, 4, 5, 6, 7, 8, 9, Array(3)]

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

In the above example we are calling flat function multiple time.

Flatten the array with passing depth

var arr = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]]

arr.flat(1) //[1, 2, 3, 4, 5, 6, Array(4)]

arr.flat(2) //[1, 2, 3, 4, 5, 6, 7, 8, 9, Array(3)]

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

If we don't know what will be the depth for an array then we can also pass Infinity as depth.

var arr = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12]]]]

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

Array.prototype.flat() function removes the empty element too.

var arr = [1, , 3, , 5, [6, , 7, [8, , 9]]]

arr.flat() //[1, 3, 5, 6, 7, Array(3)]

arr.flat(Infinity) //[1, 3, 5, 6, 7, 8, 9]

Note

Array.prototype.flat() function is available nodejs version 11. And still it is not supported by Internet Explorer. For that you can use Polyfill.

Browser compatibility of Array.prototype.flat()

Ployfill for Array.prototype.flat()

😊😊😊

Sourabh Somani
He is Microsoft MVP & C# Corner MVP. His core competencies include Mobile and web applications development using .NET, Python, Node.js, C#, JavaScript, jQuery, SQL Server, NoSQL, MongoDB, and Angular.
Chittorgarh, Rajasthan, India