September 3, 2010

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.


'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "MultiDimensional Array in JavaScript"
  1. Elijah Manor said...
    September 3, 2010 8:55 AM

    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/

  2. Suprotim Agarwal said...
    September 3, 2010 10:08 AM

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

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

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions