Open In App

TypeScript Array flat() Method

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript flat() method of Arrays allows you to create an array while preserving the one.

It combines all the elements from sub-arrays, adds them to the parent array, to the specified depth, and enables you to merge a sub-array into its parent array without modifying the structure.

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.

Example 1: In this example we will flat a single-level nested array.

Javascript




// This is a nested array
const nestedArray: number[][] =
    [[1, 2, 3], [4, 5], [6]];
// Here we are falttening nested array
const flattenedArray: number[] =
    nestedArray.flat();
 
console.log(flattenedArray);


Output:

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

Example 2: In this example, we will flat a multi-level nested array.

Javascript




// This is a nested array
const deeplyNestedArray: number[][][] =
    [[1, [2, 3]], [[4], 5, [6]]];
// Here we are falttening nested array
const flattenedDeepArray: number[] =
    deeplyNestedArray.flat(2);
 
console.log(flattenedDeepArray);


Output:

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads