How to Create a Two Dimensional Array in JavaScript
The two-dimensional array is a set of items sharing the same name. The two-dimensional array is an array of arrays, that is to say, to create an array of one-dimensional array objects. They are arranged as a matrix in the form of rows and columns.
JavaScript suggests some methods of creating two-dimensional arrays.
How to Create a Two-Dimensional Array?
To create a two-dimensional array in JavaScript, you can use an array of arrays. Here's an example:
var myArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
In this example, we have a two-dimensional array with three rows and three columns. Each row is an array containing three values.
To access an element in a two-dimensional array, you can use two sets of square brackets. The first set of brackets specifies the row, and the second set of brackets specifies the column. For example:
In this example, we've accessed the element in the second row and third column of the array (with indices 1 and 2, respectively), which has a value of 6.
You can also use loops to iterate over the elements in a two-dimensional array. For example:
Array Constructor
You can use the array constructor and the for loop to create a 2D array like this:
In this example, we've used two nested loops to iterate over each element in the array and print its value to the console.
Array Literal Notation
Lieteral notation method can also be used to create 2D arrays:
The Array.from() method
The Array.from() method will return an array object from any JavaScript object with the length property or an iterable object.
The Array.prototype.map()Method
You can also call the map() function directly:
Multidimensional Arrays
Multidimensional arrays are known in JavaScript as arrays inside another array as they are created by using another one-dimensional array.
They can have more than two dimensions. A two-dimensional array is also called a matrix or a table of rows and columns.