Skip to content

JavaScript flatten array of arrays | Example code

  • by

Use the concat() method to flatten an array of arrays (merge arrays) in JavaScript. Using the apply method of concat will just take the second parameter as an array.

var merged = [].concat.apply([], arrays);

There is also the Array.prototype.flat() method (introduced in ES2019) that you could use to flatten the arrays.

const flatarr = arrays.flat(1);

//The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

JavaScript flattens an array of arrays

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    var arrays = [["6"],["12"],["25"],["25"],["18"],["22"],["10"]];
    var merged = [].concat.apply([], arrays);

    console.log(merged);
  </script>

</body>
</html> 

Output:

JavaScript flatten array of arrays

How to flatten nested array in JavaScript?

Answer: The flat() method concatenated all the elements of the nested array [3,4,5] to the elements of the new array.

const numbers = [1, 2, [3, 4, 5]];
const flatNumbers = numbers.flat();

console.log(flatNumbers);

Output: [1, 2, 3, 4, 5]

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

Leave a Reply

Discover more from Tutorial

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

Continue reading