MultiDimensional Array in JavaScript

Although JavaScript does not provide inbuilt support for MultiDimensional Arrays, however you can create a multidimensional array by creating a new array as an element of an existing array. In this example, we will see how to create a 3x3 matrix in JavaScript

<script type="text/javascript">

// declare array of multi dimensions
var arrOfArr = new Array(3);
// or declare as [[],[],[]] as suggested by Elijah

// allocate storage
for (var x = 0; x < arrOfArr.length; x++) {
arrOfArr[x] = new Array(3);
}

// Populate the array
// first array
arrOfArr[0][0] = "00";
arrOfArr[0][1] = "01";
arrOfArr[0][2] = "02";

// second array
arrOfArr[1][0] = "10";
arrOfArr[1][1] = "11";
arrOfArr[1][2] = "12";

// third array
arrOfArr[2][0] = "20";
arrOfArr[2][1] = "21";
arrOfArr[2][2] = "22";

alert(arrOfArr);
</script>



Although here arrOfArr seems to be a one-dimensional array, each elements of the array is initialized with another 1-D array, thus making it an array of array i.e. 2-D array.

Similarly for a three-dimensional array, you would declare the array using

arrOfArr[x][y] = new Array();

and then use it using the following code:

arrOfArr[0][0][3] = "some value";

and so on.





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Test said...

Douglas Crockford recommends using the [] syntax to create new Arrays.

You could change the above code to look something like the following instead

var arrOfArr = [[], [], []];

http://jsfiddle.net/Hv4Py/

Suprotim Agarwal said...

Thanks Elijah. I have made a small comment in the post mentioning that.

Any reason why is this way of declaring an array preferred?