Skip to content

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.

If you’re working with an older version of JavaScript, you can use the reduce() method to flatten the array manually.

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 ]

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading