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 many ways:
Approach 1: Using a nested for loop
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
for (let i = 0; i < row; i++) {
gfg[i] = [];
for (let j = 0; j < col; j++) {
gfg[i][j] = h++;
}
}
console.log(gfg);
|
Output
[ [ 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
let gfg = new Array(3);
for (let i = 0; i < gfg.length; i++) {
gfg[i] = [];
}
let h = 0;
let s = "GeeksforGeeks";
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
gfg[i][j] = s[h++];
}
}
console.log(gfg);
|
Output
[ [ 'G', 'e', 'e' ], [ 'k', 's', 'f' ], [ 'o', 'r', 'G' ] ]
Approach 2: Use the literal notation
Example: 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' ]
]
The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object.
Example:
Javascript
const rows = 3;
const columns = 4;
const matrix = Array.from({ length: rows }, () =>
new Array(columns).fill(0));
console.log(matrix);
|
Output
[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
In this method, we will use the fill() method and map method for creating the two-dimensional array in Javascript.
Example:
Javascript
const rows = 3;
const columns = 4;
const matrix = Array(rows).fill().map(() =>
Array(columns).fill(0));
console.log(matrix);
|
Output
[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!