Related Articles

• Write an Interview Experience

How to flatten a given array up to the specified depth in JavaScript ?

• Last Updated : 08 Apr, 2021

In this article, we will learn how to flatten a given array up to the specified depth in JavaScript.

The flat() method in JavaScript is used to flatten an array up to the required depth. It creates a new array and recursively concatenates the sub-arrays of the original array up to the given depth. The only parameter this method accepts is the optional depth parameter (by default: 1). This method can be also used for removing empty elements from the array.

Syntax:

`array.flat(depth);`

Example:

HTML

 `<``html``>``  ``<``body``>``    ``<``h1` `style``=``"color: green;"``>``      ``GeeksforGeeks``    ````    ``<``b``>``      ``How to flatten a given array up to ``      ``the specified depth in JavaScript?``    ````    ``<``script``>`` ` `      ``// Define the array``      ``let arr = [1, [2, [3, [4, 5], 6], 7, 8], 9, 10];`` ` `      ``console.log("Original Array:", arr);`` ` `      ``let flatArrOne = arr.flat();`` ` `      ``console.log(``        ``"Array flattened to depth of 1:",``        ``flatArrOne``      ``);`` ` `      ``let flatArrTwo = arr.flat(2);`` ` `      ``console.log(``        ``"Array flattened to depth of 2:",``        ``flatArrTwo``      ``);`` ` `      ``let flatArrThree = arr.flat(Infinity);`` ` `      ``console.log(``        ``"Array flattened completely:",``        ``flatArrThree``      ``);``    ````  `````

Output:

```Original Array: [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]
Array flattened to depth of 1: [1, 2, [3, [4, 5], 6], 7, 8, 9, 10]
Array flattened to depth of 2: [1, 2, 3, [4, 5], 6, 7, 8, 9, 10]
Array flattened completely: [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]```

My Personal Notes arrow_drop_up