How to Use the flat() method of Array in JavaScript
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Example of flat() method 1:-
const array1 = [1, 2, 3, [4, 5]];
console.log(array1.flat());
// Output: Array [1, 2, 3, 4, 5]
Example of flat() method 2:-
const array2 = [1, 2, 3, [4, [5, [6, 7]]]];
console.log(array2.flat());
// Output: Array [1, 2, 3, 4, Array [5, Array [6, 7]]]
Example of flat() method 3 by specifying the depth:-
The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
const array3 = [1, 2, [3, [4, [5, 6]]]];
console.log(array3.flat(2));
// Output: Array [1, 2, 3, 4, Array [5, 6]]
Example of flat() method 4 by specifying the depth:-
const array4 = [1, 2, [3, [4, [5, 6]]]];
console.log(array4.flat(Infinity));
// Output: Array [1, 2, 3, 4, 5, 6]
Leave a Reply