How To Create A Two Dimensional Array In JavaScript

create a two dimensional array in javascript

JavaScript does not have true multidimensional arrays. However, you can fake it by creating an array of arrays. Here is how to create a two dimensional array in JavaScript:

var arr = [[1,2], [3,4], [5,6]];

This would create an array with three elements, each of which is an array with two elements. Accessing arr would look like this:

console.log(arr[0]); //[1,2]

console.log(arr[1]); //[3,4]

console.log(arr[2]); // [5,6]

Accessing an element within one of the sub-arrays would look like this:

console.log(arr[0][1]); //2

console.log(arr[1][0]); //3

console.log(arr[2][1]); //6 

If you wanted to create a true 2D array without any initial values, you would need to do something like this:

var rows = 3;

var columns = 3;

var arr = new Array(rows);

for (var i=0;i<arr.length;i++) {

arr[i] = new Array(columns);

}

This would create an array with the desired number of rows and columns. Accessing elements would work the same way as the previous example.

You can use two for loops to create and populate a 2D array with initial values:

var rows = 3;

var columns = 4;

let arr = [];

for (var i=0;i<rows;i++) {

for (var j=0;j<columns;j++) {

   arr[i] = [];

}

}

for(var i=0;i<rows;i++) {

for(var j=0;j<columns;j++) {

  arr[i][j] = j;

}

}

console.log(arr);

This would create an array with 3 rows and 4 columns. The first nested loop creates the necessary number of sub-arrays, and the second nested loop populates each sub-array with consecutive numbers starting from 0.

Creating a 2D array this way has some advantages and disadvantages. The advantage is that you can dynamically change the size of the array at runtime. The disadvantage is that you have to use two for loops instead of one to access elements, which can make your code more difficult to read and write.

Another option is to use an array of objects:

var arr = [];

arr.push({x:1, y:2});

arr.push({x:3, y:4});

arr.push({x:5, y:6});

Accessing elements would look like this:

console.log(arr); //[{x:1, y:2}, {x:3, y:4}, {x:5, y:6}]

console.log(arr.length); //3

console.log(arr[0]); //{x:1, y:2}

console.log(arr[1]); //{x:3, y:4}

console.log(arr[2]); //{x:5, y:6}

This method has the advantage of being easier to read and write than the previous method. The disadvantage is that you cannot dynamically change the size of the array at runtime.

Conclusion – Create A Two Dimensional Array In JavaScript

There are several ways to create a 2D array in JavaScript. The most common method is to use an array of arrays, but you can also use an array of objects. Each method has its own advantages and disadvantages. Choose the method that is most appropriate for your particular situation.

Leave a Reply