The flat function in JavaScript is used to flatten a nested array.
For example, if an array exists within an array, the flat function can be used to concatenate the two arrays into one. One can do this by merging the inner array elements with those of the outer one.
The
flatfunction also removes any empty spaces.
flat()
OR
flat(depth)
The flat function takes up to 1 argument:
depth - a value to limit flattening to a certain depth or nesting level. For instance, a depth of 1 will only flatten a 2D array.
depthis an optional parameter. By default, it is assumed to be 1.
The flat function returns the flattened array.
The program below declares a nested array with a depth of 2. The flat function is called without specifying depth; hence, it is assumed to be 1.
The first call to flat partially flattens the array; subsequently, flat is called again with a depth of 2. The original array is now fully flattened.
The previous and modified arrays are printed using the console.log function so that you can observe the differences between them.
Free Resources