How to create two dimensional array in JavaScript?
The two-dimensional array is a collection of items which share a common name and they are organized as a matrix in the form of rows and columns. The two-dimensional array is an array of arrays, so we create an array of one-dimensional array objects.
The following program shows how to create an 2D array :
Example-1:
<script> // Create one dimensional array var gfg = new Array(2); document.write("Creating 2D array <br>"); // Loop to create 2D array using 1D array for (var i = 0; i < gfg.length; i++) { gfg[i] = new Array(2); } var h = 0; // Loop to initilize 2D array elements. for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { gfg[i][j] = h++; } } // Loop to display the elements of 2D array. for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { document.write(gfg[i][j] + " "); } document.write("<br>"); } </script> |
chevron_right
filter_none
Output:
Creating 2D array 0 1 2 3
Example-2:
<script> // Create one dimensional array var gfg = new Array(3); // Loop to create 2D array using 1D array document.write("Creating 2D array <br>"); for (var i = 0; i < gfg.length; i++) { gfg[i] = []; } var h = 0; var s = "GeeksforGeeks"; // Loop to initilize 2D array elements. for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { gfg[i][j] = s[h++]; } } // Loop to display the elements of 2D array. for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { document.write(gfg[i][j] + " "); } document.write("<br>"); } </script> |
chevron_right
filter_none
Output:
Creating 2D array G e e k s f o r G
Recommended Posts:
- Transpose a two dimensional (2D) array in JavaScript
- Create a comma separated list from an array in JavaScript
- How to create a link in JavaScript ?
- Object.create( ) In JavaScript
- How to create a style tag using JavaScript?
- Create a string with multiple spaces in JavaScript
- How to create multi-line strings in JavaScript?
- How to create an array for JSON using PHP?
- Create a Pandas Series from array
- How to create comma separated list from an array in PHP ?
- Multi-dimensional lists in Python
- JavaScript | Array pop()
- RMS Value Of Array in JavaScript
- JavaScript | Array lastIndexOf()
- JavaScript | Array slice()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



