JavaScript(JS) array method - flat
The flat()
method is an array method in JavaScript that creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. It flattens an array of nested arrays into a single level array.
Here's the syntax of the flat()
method:
array.flat(depth);ww:ecruoSw.theitroad.com
array
is the array that theflat()
method is called on.depth
is an optional argument that specifies the depth of the flattening. The default value is1
, which means that theflat()
method will only flatten one level of nested arrays. A value ofInfinity
will flatten all nested arrays.
The flat()
method does not modify the original array. It returns a new flattened array.
Here's an example of how to use the flat()
method:
let array = [1, 2, [3, 4], [[5, 6], 7]]; let flattenedArray = array.flat(); console.log(flattenedArray); // [1, 2, 3, 4, 5, 6, 7]
In this example, we have an array array
containing the elements [1, 2, [3, 4], [[5, 6], 7]]
. We use the flat()
method to flatten the nested arrays into a single level array. The console.log()
statement outputs the value of flattenedArray
, which is [1, 2, 3, 4, 5, 6, 7]
.
Note that the flat()
method was introduced in ECMAScript 2019, so it may not be supported by older browsers. If you need to flatten an array in older browsers, you can use the reduce()
method to concatenate the sub-arrays manually.