Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to create two dimensional array in JavaScript ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.

We can create a 2D array in two ways:

  • Using a nested for loop
  • Array manually with the array literal notation

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




let gfg = [];
let row = 3;
let col=3;
let h=0
 
// Loop to initialize 2D array elements.
for (var i = 0; i < row; i++) {
    gfg[i]=[];
    for (var j = 0; j < col; j++) {
        gfg[i][j] = h++;
    }
}
console.log(gfg);

Output: 

Creating 2D array
[ 
 [ 0, 1, 2 ], 
 [ 3, 4, 5 ], 
 [ 6, 7, 8 ] 
]

Example 2: In this example, we will create a two-dimensional array using string values. 

javascript




var gfg = new Array(3);
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++];
    }
}
console.log(gfg);

Output: 

[ [ 'G', 'e', 'e' ], [ 'k', 's', 'f' ], [ 'o', 'r', 'G' ] ]

Example 3: In this example, we will create a 2D array manually. This is the 2D array that stores the information of the student.

Javascript




let MathScore = [
    ["Bar", 20, 60, "A"],
    ["Foo", 10, 52, "B"],
    ["Joey", 5, 24, "F"],
    ["John", 28, 43, "A"],
    ["Liza", 16, 51, "B"]
];
console.log(MathScore);

Output:

[
  [ 'Bar', 20, 60, 'A' ],
  [ 'Foo', 10, 52, 'B' ],
  [ 'Joey', 5, 24, 'F' ],
  [ 'John', 28, 43, 'A' ],
  [ 'Liza', 16, 51, 'B' ]
]

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.


My Personal Notes arrow_drop_up
Last Updated : 26 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials