#

# Q365 How do I create a multi-dimensional array in Javascript?

You are here: irt.org | FAQ | JavaScript | Object | Q365 [ previous next ]

JavaScript does not support real multi-dimensional arrays. You can however simulate multi-dimensional arrays using two different techniques:

```<SCRIPT LANGUAGE="JavaScript"><!--
//  Arrays within arrays:

var x = new Array(new Array(1,2,3),new Array('A','B','C'),new Array('x','y','z'));

//  Associative arrays:

var myArray = new Array();
myArray['00'] = 1;
myArray['01'] = 2;
myArray['02'] = 3;
myArray['10'] = 'A';
myArray['11'] = 'B';
myArray['12'] = 'C';
myArray['20'] = 'x';
myArray['21'] = 'y';
myArray['22'] = 'z';

alert(myArray['1' + '2']);  // returns 'C';
//--></SCRIPT>```

The following was submitted by Antti Eronen

You can use the code submitted below to easily create 3D-arrays. The code is hopefully self-explanatory enough. You could tweak this code to create a new function for creating 4D-arrays etc, or...

Someone with more time on her hands could create a recursive version of this for creating arrays of any number of dimensions. I didn't have the time or energy right now.

```<script language="JavaScript"><!--
// Create a new array variant for your use
var y = new Array()

// Below you create an array of chosen 'dimensions'
y = create3DArray(6,6,6) // creates a 6 x 6 x 6 array

// Show the contents of a few arbitrary cells

function create3DArray(d1, d2, d3) {
var lineTxt = "5";

var x = new Array(d1);

for (var i=0; i < d1; i++) {
x[i] = new Array(d2);
}

for (var i=0; i < d1; i++) {
for (var j=0; j < d2; j++) {
x[i][j] = new Array(d3);
}
}

// By uncommenting the next lines you can set the array cells
// to a preliminary value (to zero below)
// Otherwise the cells are left to the undefined value
//  for (var i=0; i < d1; i++) {
//    for (var j=0; j < d2; j++) {
//      for (var k=0; k < d3; k++) {
//        x[i][j][k] = 0;
//      }
//    }
//  }

return x;
}
//--><script>```