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.


Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

Elijah Manor 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?