JavaScript Array flat()
Syntax & Examples
Array.flat() method
The flat() method of the Array class in JavaScript returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Syntax of Array.flat()
There are 2 variations for the syntax of Array.flat() method. They are:
flat()
This method returns a new array with all sub-array elements concatenated into it recursively up to a depth of 1.
Returns value of type Array
.
flat(depth)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
depth | optional | The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. |
This method returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Returns value of type Array
.
✐ Examples
1 Using flat() method to flatten an array with default depth
In JavaScript, we can use the flat() method to flatten an array with the default depth of 1.
For example,
- We define an array variable arr with nested elements [1, [2, [3, [4]], 5]].
- We use the flat() method on arr to flatten it with the default depth of 1.
- The result is stored in the variable flattenedArr.
- We log flattenedArr to the console using console.log() method to see the flattened array.
JavaScript Program
const arr = [1, [2, [3, [4]], 5]];
const flattenedArr = arr.flat();
console.log(flattenedArr);
Output
[1, 2, [3, [4]], 5]
2 Using flat() method to flatten an array with specified depth
We can use the flat() method to flatten an array to a specified depth.
For example,
- We define an array variable arr with nested elements [1, [2, [3, [4]], 5]].
- We use the flat() method on arr with the depth parameter set to 2.
- The result is stored in the variable flattenedArr.
- We log flattenedArr to the console using console.log() method to see the flattened array.
JavaScript Program
const arr = [1, [2, [3, [4]], 5]];
const flattenedArr = arr.flat(2);
console.log(flattenedArr);
Output
[1, 2, 3, [4], 5]
Summary
In this JavaScript tutorial, we learned about flat() method of Array: the syntax and few working examples with output and detailed explanation for each example.