#JavaScript flat()
The flat()
method is an in-built JavaScript array method that can be used to create a new array that is flattened from a multi-dimensional array. It returns a new array that is a one-dimensional flattened version of the original array. This method can be useful when working with data arrays in JavaScript.
Syntax
The basic syntax of the flat()
method is as follows:
array.flat(depth);
Where array
is the array to be flattened and depth
is an optional parameter that specifies the maximum nested depth to flatten the array to.
Example
Let's consider an example where we have to flatten an array:
let multiDimensionalArray = [1, 2, [3, 4, [5, 6]]];
let flattenedArray = multiDimensionalArray.flat();
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
In the above example, the flat()
method is used on the multiDimensionalArray
to return a new one-dimensional array, flattenedArray
.
Output
The output of the above example will be as follows:
[1, 2, 3, 4, 5, 6]