JavaScript flat() Method | Array.prototype.flat() Tutorial

JavaScript flat() method example | JavaScript array flat() tutorial is the topic that we are going to understand today.

JavaScript is becoming the most popular programming language in the world. In this tutorial, we are going to understand a cool new feature that has been added to the ES10/ES2019 standards.

JavaScript Array flat() Definition

The flat() method creates and returns a new array with all sub-array elements merging into it recursively up to the specified depth.

JavaScript flat() Syntax

var new_array = array.flat([depth]);

new_array – A new array with the sub-array elements concatenated into it.

depth – The depth level specifies how deep a nested array structure should be flattened.

Here, the point to be noted that if the depth value is not provided, it assumes default depth value 1.

JavaScript Array flat() Example

Let’s say we have created an array with sub-array and we want these all sub-array elements concatenated into one single array like this:

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

// We want output like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Now, what will you do to solve this? Here flat method comes into the picture. See the code below.

Flattening Nested Arrays

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

var new_array = array.flat()
// new_array will print [1, 2, 3, 4, 5, 6, Array(4)]

var new_array = array.flat(2)
// new_array will print [1, 2, 3, 4, 5, 6, 7, 8, 9, Array(3)]


var new_array = array.flat(3)
// new_array will print [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

As you can see, Using this method we can flatten array to get our results. If you know the depth, you can pass it like 1, 2, or any number.

You can also use Infinity if you need to flatten an array of the arbitrary depth or you don’t know the depth.

Flattening and Array Holes

You can also remove empty slots in an array using the this method:

var arr = [1, 2, , 4, 5, 6];
arr.flat();

// Output - [1, 2, 4, 5, 6]

JavaScript flat() Alternative

You can use JavaScript reduce and concatenate to flat single or deep level array.

To flat single-level array:

var array1 = [1, 2, [3, 4]];

//to flat single level array
array1.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4]

We can use recursion with reduce and concat method to enable deep level flatten.

var array1 = [1,2,3,[1,2,3,4, [2,3,4]]];

function flattenDeepLevel(array1) {
   return array1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeepLevel(val)) : acc.concat(val), []);
}

flattenDeepLevel(array1); // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

Finally. JavaScript flat method tutorial with example is over, Hope you understood the concept.

You can also read about JavaScript reduce() method in detail.

One Response

  1. Md Rakib January 29, 2020

Leave a Reply