TypeScript Array flat() Method
Last Updated :
29 Jan, 2024
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
const nestedArray: number[][] =
[[1, 2, 3], [4, 5], [6]];
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
const deeplyNestedArray: number[][][] =
[[1, [2, 3]], [[4], 5, [6]]];
const flattenedDeepArray: number[] =
deeplyNestedArray.flat(2);
console.log(flattenedDeepArray);
|
Output:
[1, 2, 3, 4, 5, 6]
Share your thoughts in the comments
Please Login to comment...