JavaScript Array flat() Method
The Javascript arr.flat() method was introduced in ES2019. The flat()
method in JavaScript creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. If no depth is provided, it defaults to 1.
Syntax:
arr.flat([depth])
Parameters:
This method accepts a single parameter as mentioned above and described below:
- depth: It specifies, how deep the nested array should be flattened. The default value is 1 if no depth value is passed as you guess it is an optional parameter.
Return value:
It returns an array i.e. depth levels flatter than the original array, it removes nesting according to the depth levels.
Example 1: Flattening a Multilevel Array
The code initializes a multilevel array, then applies the flat() method with Infinity parameter to recursively flatten all nested arrays into a single-level array. The result is logged.
// Creating multilevel array
const numbers = [['1', '2'], ['3', '4',
['5', ['6'], '7']]];
const flatNumbers = numbers.flat(Infinity);
console.log(flatNumbers);
Output
[ '1', '2', '3', '4', '5', '6', '7' ]
Example 2: Flattening Nested Arrays with flat() Method
The code demonstrates flattening a nested array to different levels using the flat() method. It applies flat() with various depth parameters (0, 1, 2) to flatten nested arrays accordingly and logs the results.
let nestedArray = [1, [2, 3], [[]],
[4, [5]], 6];
let zeroFlat = nestedArray.flat(0);
console.log(
`Zero levels flattened array: ${zeroFlat}`);
// 1 is the default value even
// if no parameters are passed
let oneFlat = nestedArray.flat(1);
console.log(
`One level flattened array: ${oneFlat}`);
let twoFlat = nestedArray.flat(2);
console.log(
`Two level flattened array: ${twoFlat}`);
// No effect when depth is 3 or
// more since array is already
// flattened completely.
let threeFlat = nestedArray.flat(3);
console.log(
`Three levels flattened array: ${threeFlat}`);
Output
Zero levels flattened array: 1,2,3,,4,5,6 One level flattened array: 1,2,3,,4,5,6 Two level flattened array: 1,2,3,4,5,6 Three levels flattened array: 1,2,3,4,5,6
Note: For depth greater than 2, the array remains the same, since it is already flattened completely.
Example 3: Flattening an Array with undefined Element
This code creates an array arr
with elements [1, 2, 3, empty, 4]
. When flat()
is called on arr
, it removes the empty slot and creates a new flattened array newArr
with elements [1, 2, 3, 4]
, which is then logged to the console.
let arr = [1, 2, 3, , 4];
let newArr = arr.flat();
console.log(newArr);
Output
[ 1, 2, 3, 4 ]
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.