JavaScript – Flatten an Array
To flatten an Array in JavaScript, call flat() method on this array. flat() method returns a new array with the contents of the original array flattened to a one-dimensional array.
Examples
In the following script, we take a two dimensional array arr
, and flatter it using Array.flat() method.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var arr = [['apple', 'banana'], ['cherry', 'mango']];
var result = arr.flat();
document.getElementById('output').innerHTML = result;
</script>
</body>
</html>
In the following script, we take a three-dimensional array arr
, and flatter the array.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var arr = [[[2, 1], [4, 8]], [[6, 0], [7, 9]]];
var result = arr.flat();
document.getElementById('output').innerHTML = result;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we have learnt how to use Array.flat() method to flatten a multi-dimensional array into a one-dimensional array with examples.