Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Last Updated : 21 Dec, 2022
Improve Article
Save Article

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




<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <b>
        How to flatten a given array up to
        the specified depth in JavaScript?
    </b>
    <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
        );
    </script>
</body>


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
Related Articles

Start Your Coding Journey Now!