Appearance
How to Create a Two Dimensional Array in JavaScript
A two-dimensional array is an array of arrays, 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:
javascript
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:
How to Create a Two-Dimensional Array in JavaScript?
Output appears here after Run.
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:
Example of iterating over the elements in a two-dimensional array in JavaScript
Output appears here after Run.
Array Constructor
You can use the array constructor and the for loop to create a 2D array like this:
Javascript array constructor
Output appears here after Run.
In this example, we've used a loop to initialize each row as a separate array.
⚠️ Important: When creating 2D arrays, avoid using
Array.fill()with an existing array, as it copies the reference rather than creating new instances. This causes all rows to share the same memory address, leading to unexpected mutations when modifying a single row.
Array Literal Notation
The literal notation method can also be used to create 2D arrays:
Javascript array literal notation
Output appears here after Run.
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.
Javascript Array.from() method
Output appears here after Run.
The Array.prototype.map() Method
You can also call the map() function directly:
How to Create a Two Dimensional Array in JavaScript
Output appears here after Run.
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.