JavaScript Tips & Tutorials

JavaScript: Multi-dimensional Array

In JavaScript, you initiate an array of 3 elements by:

var myArray = new Array(3);


var myArray = ['', '', ''];

And then to populate them with some values, you need:

	myArray[i] = i;

This is pretty much a single dimensional array. To create a multi-dimensional array such as a 2 dimensional one, you need to add one more dimension, initiating yet another array for each of the 1st-dimension elements:

var myArray = new Array(3);

	myArray[i] = new Array(3);
		myArray[i][j] = '';

A more straightforward approach is to directly assign values to multi-dimensional array variables:

myArray[0][0] = '';
myArray[0][1] = '';
myArray[0][2] = '';
myArray[1][0] = '';
myArray[1][1] = '';
myArray[1][2] = '';
myArray[2][0] = '';
myArray[2][1] = '';
myArray[2][2] = '';

By Yang Yang


17 replies on “JavaScript: Multi-dimensional Array”


var new_array = {
0: “Hi”,
1: “all”,
2: “my”,
3: “name”,
4: “is”,
5: “Andrey”


Thanks for the information. I would suggest never presenting an example when the array is a square, e.g. 3×3. Use 2×3 or 3×4 or whatever. When it’s a square (e.g. 3×3), then when one sees the parameter “3”, it isn’t immediately obvious if that’s the column number or the row number.



Actually, there is no such thing as ‘row’ and ‘column’ for arrays.
They are simply [‘first dimension identifier’] and [‘second dimension identifier’]

A simpler way to create a multi dimensional array is like this:

var myArray = new Array(new Array(new Array())));

myArray[1][2][3] = “the 3rd dimension”;

I want something, such as a jquery script, that executes a python script that does nothing more than immediately display a line of HTML chosen based on the url of the calling HTML page, immediately upon page open or refresh, a different line for each URL. Initially, it can show just the URL, but the eventual solution is to use the URL as a dictionary key to select the line as a value of that dictionary.

on a technical note, the use of new Array() is highly discouraged these days, and the format is instead just

var myarray = [];
var i = 3;
while(i–>0) { myarray[i] = i; }

As there is no such thing as a size-restricted array in JavaScript, using new Array(size) actually “lies” about what your code will do.

Additionally, putting a “var i” inside a for loop doesn’t do the same as most programming language: variables are function-scoped, not logic-scoped, so for(var i; …) is the same as

var i;
for(;i<…) { … }

Thank you! Your post was very useful for me.

Another way to create Multidimensional arrays:

// Adapted from VBScript: Multidimensional array:
var section = new Array(1);
var key = new Array(1);

section[1] = ["i18n"];
key[1] = ["Load"];

// add array key to section.
// array inside array
section[1] = key;

section[1][1] = language;
alert("Section[i18n][Load]: " + section[1][1]);

var myvar =
“no “:{“a”:[‘g’,’h’],’b’:[‘i’,’j’],’c’:[‘k’,’l’,’m’]},

Comments are closed.