Create a 2-dimensional array in JavaScript
This post will discuss how to create a two-dimensional array in JavaScript.
JavaScript offers several ways to create a two-dimensional array of fixed dimensions:
1. Using Array constructor
Using the array constructor and the for-loop, creating a two-dimensional array in JavaScript is as simple as:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
const M = 3, N = 4; var arr = new Array(M); // create an empty array of length `M` for (var i = 0; i < M; i++) { arr[i] = new Array(N); // make each element an array } console.log(arr); /* Output: [ [ <4 empty items> ], [ <4 empty items> ], [ <4 empty items> ] ] */ |
2. Using array literal notation
2D Arrays can be created using the literal notation, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
const M = 3, N = 4; // Note 2nd dimension is not relevant here var arr = []; for (var i = 0; i < M; i++) { arr[i] = []; } console.log(arr); /* Output: [ [], [], [] ] */ |
3. Using Array.from() function
The Array.from() method creates a new Array instance from the specified array and optionally map each array element to a new value. To create a 2D array, the idea is to map each element of the length of M to a new empty array of length N.
|
1 2 3 4 5 6 7 8 |
const M = 3, N = 4; var arr = Array.from(Array(M), () => new Array(N)); console.log(arr); /* Output: [ [ <4 empty items> ], [ <4 empty items> ], [ <4 empty items> ] ] */ |
4. Using Array.prototype.map() function
Alternatively, you can directly call the map() function on the array, as shown below:
|
1 2 3 4 5 6 7 8 |
const M = 3, N = 4; var arr = Array(M).fill().map(() => Array(N)); console.log(arr); /* Output: [ [ <4 empty items> ], [ <4 empty items> ], [ <4 empty items> ] ] */ |
That’s all about creating a two-dimensional array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)