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.

Array Constructor

You can use the array constructor and the for loop to create a 2D array like this:

const m = 4;
const  n = 5;
let arr = new Array(m); // create an empty array of length n
for (var i = 0; i < m; i++) {
  arr[i] = new Array(n); // make each element an array
}
console.log(arr); //  Output: [ [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ] ]

Array Literal Notation

Lieteral notation method can also be used to create 2D arrays:

const m = 4;
const  n = 5; // Note 2nd dimention is not relevant here
let arr = [];
for (var i = 0; i < m; i++) {
  arr[i] = [];
}
console.log(arr); // Output: [ [], [], [], [] ]

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.

const m = 4;
const  n = 5;
let arr = Array.from(Array(m), () => new Array(n));
console.log(arr); //  Output: [ [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ] ]

The Array.prototype.map()Method

You can also call the map() function directly:

const m = 4;
const  n = 5;
let arr = Array(m).fill().map(() => Array(n));
console.log(arr);  //  Output: [ [ <5 empty items> ], [ <5 empty items> ], [ <5 empty items> ], , [ <5 empty items> ] ]

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.

Do you find this helpful?

Related articles