Use of flat Array Method in JavaScript?
We mainly use flat method basicaly to convert an original array into a new array. And this is done by collecting and concating the sub-arrays in an array into a single array. And one important fact about the flat array method is that we can compute the original into another array based on the depth of the array. And this method is really very useful because it makes computing the oeprations of an array much easier.
Example of flat() array method with syntax
(1)Syntax for flat array methods
array.flat(depth);
Here depth value is 1 by default and you can leave it empty. The depth value takes a number as its data type.
here array.flat(1) is equal to array.flat(). And array.flat(2) means depth above 2.
(2)Now flat() array method example 2
const arrExample=[1, 2, [3, 4, 5], 6, 7, 8];
arr.flat();
here expected output is
[1, 2, 3, 4, 5, 6, 7, 8]
in above array sub-array is [3,4,5].
Here is above example we use flat method to concatenate the two array together in a single array.
(3)Array method example 3
const arr2Example=[[[1, 2], 3, 4, 5]];
console.log(arr2Example.flat(2));
now output of above is
[1, 2, 3, 4, 5]
Here in above method we use depth value 2 to concatenate two array into a single array. | |