How to create two dimensional array in JavaScript ?
The two-dimensional array is a collection of items that 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 a 2D array :
Example 1: In this example, we will construct a two-dimensional array using integer values.
Javascript
<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 initialize 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> |
Output:
Creating 2D array 0 1 2 3
Example 2: In this example, we will create a two-dimensional array using string values.
javascript
<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 initialize 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> |
Output:
Creating 2D array G e e k s f o r G
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Please Login to comment...