Categories
JavaScript Answers

How to convert a 2D JavaScript array to a 1D array?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *