Open In App

TypeScript Array flat() Method

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Array.prototype.flat() method in TypeScript allows you to create a new array with all sub-array elements concatenated into it, up to a specified depth. This method helps in flattening nested arrays to the desired depth, making it easier to handle deeply nested structures.

Syntax:

array.flat([depth]);

Parameters:

  • depth (optional): The depth level specifies how deep a nested array structure should be flattened. It Defaults to 1.

Return Value:

  • Flat() method returns a new array with its sub-array elements that are concatenated into it.

Examples Array flat() Method

Example 1: Flattening a Single-Level Nested Array

In this example, we will flatten a single-level nested array using the flat() method.

const singleLevelArray: number[][] = [ [1, 2], [3, 4], [5, 6] ];
const flatArray: number[] = singleLevelArray.flat();

console.log(flatArray); 

Output:

[1, 2, 3, 4, 5, 6]

Example 2: Flattening a Multi-Level Nested Array

In this example, we will flatten a multi-level nested array using the flat() method with a specified depth.

const multiLevelArray: any[] = [1, [2, [3, [4, [5, 6]]]]];
const flatArrayDepth2: any[] = multiLevelArray.flat(2);

console.log(flatArrayDepth2); 

Output:

[1, 2, 3, [4, [5, 6]]]

The Array.prototype.flat() method is used for flattening nested arrays in TypeScript. It provides flexibility with the depth parameter, allowing you to control the level of flattening according to your needs. This method is especially useful when dealing with deeply nested array structures.


Next Article

Similar Reads