A two-dimensional array, also known as a matrix, is an array that contains arrays as its elements.
In JavaScript, a two-dimensional array can be created by using an array of arrays.
This type of array is useful when we need to store multiple values in a single array.
In this tutorial, we will take a look at how to create a two-dimensional array in JavaScript and explore some of its use cases.
Declaring a Two Dimensional Array in JavaScript
There are two ways to declare a two-dimensional array in JavaScript.
The first is to use an array literal, which is a list of elements enclosed in square brackets.
The second is to use the Array constructor, which allows us to specify the length of the array.
Using Array Literals
We can declare a two-dimensional array in JavaScript using an array literal by enclosing arrays within another array.
Here’s an example of a 2×3 matrix:
var matrix = [[1, 2, 3], [4, 5, 6]];
Using the Array Constructor
We can also declare a two-dimensional array using the Array constructor, which allows us to specify the length of the array.
Here’s an example of a 2×3 matrix:
var matrix = new Array(2); for (var i = 0; i < matrix.length; i++) { matrix[i] = new Array(3); }
Accessing Elements of a Two Dimensional Array
To access the elements of a two-dimensional array, we use two nested for loops. The outer loop iterates through each row, while the inner loop iterates through each element in a row.
Here’s an example of how to access the elements of the 2×3 matrix created in the previous section:
for (var i = 0; i < matrix.length; i++) { for (var j = 0; j < matrix[i].length; j++) { console.log(matrix[i][j]); } }
Adding Elements to a Two Dimensional Array
To add elements to a two-dimensional array, we can use the same nested for loop structure we used to access its elements.
Here’s an example of how to add elements to the 2×3 matrix created earlier:
for (var i = 0; i < matrix.length; i++) { for (var j = 0; j < matrix[i].length; j++) { matrix[i][j] = i + j; } }
Use Cases
Two-dimensional arrays are useful in a variety of applications, including:
- Representing matrices in mathematics and computer science.
- Storing large amounts of data in a table-like structure.
- Implementing game boards and grid-based systems.
Conclusion
In this tutorial, we have discussed how to create a two-dimensional array in JavaScript and explored some of its use cases.