Open In App

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

Last Updated : 23 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Javascript




// 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, [Array], 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,...

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads