Sometimes, we want to convert a 2D JavaScript array to a 1D array.
In this article, we’ll look at how to convert a 2D JavaScript array to a 1D array.
How to convert a 2D JavaScript array to a 1D array?
To convert a 2D JavaScript array to a 1D array, we use the array flat
method.
For instance, we write
const arrToConvert = [
[0, 0, 1],
[2, 3, 3],
[4, 4, 5],
];
const newArr = arrToConvert.flat();
to call arrToConvert.flat
to return a flattened version of the arrToConvert
array.
Conclusion
To convert a 2D JavaScript array to a 1D array, we use the array flat
method.