• JavaScript Video Tutorials

JavaScript - Array flat() Method



The Array.flat() method in JavaScript is used to create a new array by flattening a nested array up to specified depth. Flattening an array means converting a multidimensional array into a one-dimensional array by concatenating all nested arrays or sub-arrays. If we didn't provide the 'depth' parameter to this method, it will consider '1' as the default depth value.

The JavaScript Array.flat() method returns a new flattened array instead of changing or modifying the original array. This method also removes the empty element slots in the arrays.

Syntax

Following is the syntax of JavaScript Array flat() method −

array.flat(depth);

Parameters

This method accepts only one parameter. The same is described below −

  • The depth(optional) specifies how deep the nested arrays within the original array should be flattened. By default, the depth value is 1.

Return value

This method returns a new array with all sub-array elements concatenated into it, up to the specified depth.

Examples

Example 1

In the example below, the specified animal array has one subarray. We haven't passed any value as the depth parameter to this function. As a result, it flattens the subarray in the animals array.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = [1, 2, 3, 4, [5, 6]];
      const result = animals.flat();
      document.getElementById("demo").innerHTML = result;
      //Expected Output: Array [1, 2, 3, 4, 5, 6]
   </script>
</body>
</html>

Output

As we can see the output, the array has been flattened.

1,2,3,4,5,6

Example 2

We have three subarrays in the animals array. Firstly, we haven't passed any parameter to the flat() method, so there will be two subarrays after executing this. Secondly, we have passed 2 as a parameter, so there will be only one subarray after executing this.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = [1, 2, [3, [4, [5, 6]]]];
      const result = animals.flat();
      document.getElementById("demo1").innerHTML = result;
      //Expected Output: Array [1, 2, 3, Array [4, Array [5, 6]]]
      animals.flat(2);
      document.getElementById("demo2").innerHTML = result;
      //Expected Output: Array [1, 2, 3, 4, Array [5, 6]]]
   </script>
</body>
</html>

Example 3

In here, we are passing “Infinity” as a parameter to the flat() method. As a result, it flattens all the subarrays present in the animals array −

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = [1, 2, [3, [4, [5, 6]]]];
      const result = animals.flat(Infinity);
      document.getElementById("demo").innerHTML = result;
      //Expected Output: Array [1, 2, 3, 4, 5, 6]
   </script>
</body>
</html>

Output

After executing the program, all the subarrays in the animals array are flattened.

1,2,3,4,5,6
Advertisements