In this tutorial, we will learn how to create a two-dimensional array in JavaScript dynamically. Two-dimensional arrays are especially useful when dealing with matrices, tables, or any other data types that need to be stored in rows and columns.
JavaScript does not have built-in support for two-dimensional arrays, but you can mimic them using arrays of arrays. By the end of this tutorial, you will be able to create, populate and access elements of a two-dimensional array in JavaScript.
Step 1: Initialize a Two-Dimensional Array
The first step in creating a two-dimensional array is to initialize it. To do this, declare an array and then fill it with arrays. You can define the size of each nested array as well.
Here’s an example of initializing a 3×3 two-dimensional array:
1 2 3 4 |
let matrix = new Array(3); for (let i = 0; i < matrix.length; i++) { matrix[i] = new Array(3); } |
In this example, we first create a new array called matrix
. Then, we iterate through its elements and replace them with new arrays, effectively creating a two-dimensional array.
Step 2: Fill the Two-Dimensional Array with Data
Once the two-dimensional array is initialized, you can fill it with data. To do this, iterate through the rows and columns of the array, assigning a value to each cell:
1 2 3 4 5 6 |
for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { matrix[i][j] = i * j; } } |
In this example, we use a nested loop to iterate through the two-dimensional array, setting each cell to the product of its row and column indices.
Step 3: Access Elements of the Two-Dimensional Array
To access elements of the two-dimensional array, use the square bracket notation with the row and column index:
1 |
let element = matrix[1][2]; // Access element at row 1, column 2 |
The Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Initialize a 3x3 two-dimensional array let matrix = new Array(3); for (let i = 0; i < matrix.length; i++) { matrix[i] = new Array(3); } // Fill the two-dimensional array with data for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { matrix[i][j] = i * j; } } // Access an element in the two-dimensional array let element = matrix[1][2]; // Access element at row 1, column 2 |
Output
The value of the element at row 1, column 2 is: 2
Conclusion
In this tutorial, we learned how to create, populate, and access elements in a two-dimensional array in JavaScript. Although JavaScript does not have native support for two-dimensional arrays, you can use arrays of arrays to achieve the same functionality. By following this technique, you can create matrices and other data types that rely on a grid-like structure.