JavaScript Flatten array | flat() Method

  • by

Use JavaScript flat() method to create a new Flatten array with all sub-array elements concatenated into it recursively up to the specified depth.

flat()
flat(depth)

A depth level is an option and it specifies how deep a nested array structure should be flattened. Defaults to 1.

JavaScript Flatten array

Simple example code obtaining a flattened array by specifying the depth.

<!DOCTYPE html>
<html>
<body>

  <script>
    const arr1 = [0, 1, 2, [3, 4]];
    console.log(arr1.flat());

    const arr2 = [0, 1, 2, [[[3, 4]]]];
    console.log(arr2.flat(2));
  </script>

</body>
</html> 

Output:

JavaScript Flatten array

Different methods to flatten an array

Using concat() and apply()

let arr = [
    [1, 2],
    [3, 4],
    [5, 6][7, 8, 9],
    [10, 11, 12, 13, 14, 15]
];

let flatArray = [].concat.apply([], arr);

//Output:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]

Using the spread operator

let flatArray = [].concat(...arr);

//Output:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]

Using the reduce method

let flatArray = arr.reduce((acc, curVal) => {
    return acc.concat(curVal)
}, []);

//Output:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.