The flat function is a built-in method for arrays that transforms a specified array into a new one-dimensional array. It merges all elements from the provided multidimensional array and flattens it to a defined depth. Users have the option to set the depth limit indicating how far the array should be flattened. The default depth limit is set to 1.
Syntax
var newArr=arr.flat(<depth>);
Parameters
Depth: This parameter is not mandatory and indicates the level to which an array should be flattened. The default setting for this parameter is 1.
Return
It produces a freshly generated array that encompasses all the elements of the sub-arrays concatenated together.
JavaScript Array flat Method Example
Let us examine the following examples for a clearer understanding.
Example1
An illustration of how the flat function operates on a two-dimensional array.
<html>
<head> <h5> Array Methods </h5> </head>
<body>
<script>
var arr=['a','b',['c','d']]; //given 2D array
var newArr=arr.flat(); //using flat() method
document.write("After flattening the array: "+newArr);
</script>
</body>
</html>
Output:
Example2
Evaluating a multidimensional array utilizing the flat function.
<html>
<head> <h5> Array Methods </h5> </head>
<body>
<script>
var arr=[90,18,[89,56],[13,20,[67,17]]]; //given multidimensional array
var newArr=arr.flat(); //using flat() method
document.write("After flattening the array: "+newArr);
</script>
</body>
</html>
Output:
It is evident that every element within the array is appended to the newly formed one-dimensional array.
Example3
Let's flatten an array upto a specified depth.
<html>
<head> <h5> Array Methods </h5> </head>
<body>
<script>
var arr=[90,18,[13,20,[67,17,[56,45]]]]; //given multidimensional array
var newArr=arr.flat(3); //using flat() method with a specified depth value.
document.write("After flattening the array: "+newArr);
</script>
</body>
</html>
Output:
Example4
Using flat method with depth value as infinity.
<html>
<head> <h5> Array Methods </h5> </head>
<body>
<script>
var arr=['Orange','Pineapple','Grapes',['Potato','Tomato','Carrot',['Guava','Litchi']]]; //given a multidimensional array.
var newArr=arr.flat(Infinity); //setting depth value as infinity.
document.write("After flattening the array,the new array comes out: <br> "+newArr);
</script>
</body>
</html>
Output:
Example5
Let's flatten an array with holes in between.
<html>
<head> <h5> Array Methods </h5> </head>
<body>
<script>
var arr=['John','Peter',,'Tomy',['Eni',,'Kerry']]; //given 2D array with holes in between.
var newArr=arr.flat(); //using flat() method.
document.write("After flattening the array, the holes vanishes. The new array comes out: <br> "+newArr);
</script>
</body>
</html>
Output:
It is evident that when the flat method is utilized, all elements of the array are combined into a single array while omitting any empty slots.