The Wayback Machine - https://web.archive.org/web/20211008091856/https://www.geeksforgeeks.org/javascript-array-flat-method/amp/

JavaScript Array flat() Method

Below is the example of the Array flat() method.

The arr.flat() method was introduced in ES2019. It is used to flatten an array, to reduce the nesting of an array.

The flat() method is heavily used in functional programming paradigm of JavaScript. Before flat() method was introduced in JavaScript, various libraries such as underscore.js were primarily used.

Syntax:

arr.flat([depth])

Parameters: This method accepts a single parameter as mentioned above and described below:

Return value: It returns an array i.e. depth levels flat than the original array, it removes nesting according to the depth levels.

More codes for the above function are defined as follows:

Program 1: The following code snippet shows, how flat() method works.




<script>
    let nestedArray = [1, [2, 3], [[]], 
                      [4, [5]], 6];
  
    let zeroFlat = nestedArray.flat(0);
  
    document.write(
      `Zero levels flattened array: ${zeroFlat}`);
    document.write("<br>");
  
    // 1 is the default value even
    // if no parameters are passed
    let oneFlat = nestedArray.flat(1);
  
    document.write(
      `One level flattened array: ${oneFlat}`);
    document.write("<br>");
  
    let twoFlat = nestedArray.flat(2);
  
    document.write(
      `One level flattened array: ${twoFlat}`);
    document.write("<br>");
  
    // No effect when depth is 3 or
    // more since array is already
    // flattened completely.
    let threeFlat = nestedArray.flat(3);
    document.write(
      `Three levels flattened array: ${threeFlat}`);
</script>

Output:

Zero levels flattened array: [1, [2, 3], [[]], [4, [5]], 6]
One level flattened array: [1, 2, 3, [], 4, [5], 6]
Two levels flattened array: [1, 2, 3, 4, 5, 6]
Three levels flattened array: [1, 2, 3, 4, 5, 6]

Note: For depth greater than 2, array remains the same, since it is already flattened completely.

Program 2: We can also remove empty slots or empty values in an array by using flat() method.




<script>
    let arr = [1, 2, 3, , 4];
    let newArr = arr.flat();
    document.write(newArr);
</script>

Output:

[1, 2, 3, 4]

Supported Browsers:




Article Tags :