Signup/Sign In
PUBLISHED ON: AUGUST 27, 2021

JavaScript Array.flat() Method

There are several situations in which the elements of an array are also an array. These types of arrays are known as nested arrays.

Previously, we had to use recursion to sort these kinds of arrays (nested arrays), which is quite tedious. So, to make this process easier, ECMA Script 2019 (ES10) introduced a new method known as Array.flat().

The Array.flat() method is used to flatten an array. With the help of this method, we can un-nest (flatten) the nested array within a single line.

A flatten array is an array of depth 0. The flat method takes an argument, a number that represents the depth of an array. Depth is the number of nested arrays present inside an array.

Syntax

Array.flat(depth);

Return Type

  • It returns a flattened array.

Parameters

  • The parameter depth is optional.
  • The depth level specifies how deep a nested array structure should be un-nest (flattened).
  • The default value of the depth parameter is 1.

Example 1

In JavaScript, an array can have a depth of infinity. The given array is of depth 3. We have flattened this array only till depth 2. So there is still one nested array inside the main array.

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

console.log(num.flat(2));  // output [1,2,3, Array(1)]

Example 2

In the given example, we have created a nested array arr using var keyword of depth 4. This array consists of alphabets as its elements but in the form of the nested array. So, we are going to un-nest this array using flat() method.

<!DOCTYPE html>
<html>
<head>
	<title>Array.flat()</title>
</head>
<body>
	<script type="text/javascript">
		var arr = ["S", "T", ["U", "D", "Y", ["T", "O", "N", ["I","G", ["H", "T"]]]]];
		/* Flatten till depth 2*/
		console.log(arr.flat(2));

		/* Flatten till depth 3*/
		console.log(arr.flat(3));

		/* Flatten till depth 4*/
		console.log(arr.flat(4));
	</script>
</body>
</html>

Output

In the given output, there are three arrays. The first array occurs when we have flattened the array to the depth of 2.

The second array occurs when we have flattened the array till the depth of 3, and the third array occurs when we have flattened the array till depth 4.

output

Conclusion

In this lesson, we have learned about array.flat() which was introduced in ECMA Script 2019 or ES 10. This method is used to flat the nested array in just a single line.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight