00 Votes

JavaScript: How to create and use two dimensional Arrays

Question by Compi | 2015-08-13 at 13:53

In JavaScript, you can create a normal one-dimensional array without any problems by using the following way.

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

But what about multidimensional arrays in JavaScript? In my case, I would like to create a two-dimensional array.

Does JavaScript support 2-dimensional arrays at all? And if yes, can someone tell me the exact syntax of declaring such arrays and how it is possible to access the elements?

ReplyPositiveNegative
0Best Answer0 Votes

In order to create a two-dimensional array in JavaScript, you only have to define another array as an element of an existing array. For example in like that:

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

To access those elements, you can go like that:

var a = arr[0][0];  // 1
var b = arr[0][1];  // 2
var c = arr[0][1];  // 3
var d = arr[1][0];  // 5

Of course, when working with very large arrays, this notation has its difficulties. In such a case, it might be better to use the following initialization procedure:

var arr = new Array(100);

for (var i = 0; i < 100; i++) {
   arr[i] = new Array(10);
}

Using new Array(), we are able to create a new array of a defined length. In the first line of the example, we are creating an array consisting of 100 elements. After that, we are looping through this array element for element and we are setting each element to another array consisting of 10 elements. Doing so, we are getting an array with 100 x 10 fields.

Of course, you can also access those fields via a loop.

for (var i = 0; i < 100; i++) {
  for (var j = 0; j < 10; j++) {
    arr[i][j] = i * j;
}

Here, we are going through the array with two loops and we are setting each array element to the product of the first and the second loop variable.

All of the examples are referring to two dimensional arrays. But in the same way, we can also create arrays consisting of more dimensions - finally, each element of a two-dimensional array can be another array.
2015-08-13 at 17:06

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.