MultiDimensional Arrays

What happens if the elements of an Array object are arrays themselves? The results is an Array of Arrays, also called a 2-dimensional array. This nesting of Arrays within arrays can go on for three, four, or more dimensions.

A 2-dimensional Array could, for example, be used to store sales statistics for 3 regions in 4 different Months:

var monthName = new Array("Jan.", "Feb.", "Mar.", "Apr.");
var regionName = new Array("North", "Central", "South");

var Jan = new Array(100, 120, 180);
var Feb = new Array(110, 90, 150);
var Mar = new Array(100, 115, 190);
var Apr = new Array(105, 115, 175);

var sales = new Array(Jan, Feb, Mar, Apr);

The month and region titles are assigned to 2 Arrays -- monthName and regionName. The four Arrays -- Jan, Feb, Mar, and Apr -- each contain 3 Sales Numbers, one for each Region. Finally, we combine all four into a single Array called sales.

var m, r;

document.write("<TABLE><TR><TH> Month </TH>");
for (r = 0; r < 3; r++) {
     document.write("<TH>" + regionName[r] + "</TH>");
}
document.write("</TR>");

This begins by declaring two variables, m and r. Then we write the word Month in the first cell of the table, followed by the 3 Region names. A for loop is used to loop around and display the contents of the regionName Array, one element in each cell of the top row.

for (m = 0; m < 4; m++) {
     document.write("<TR><TH>" + monthName[m] + "</TH>");
     for (r = 0; r < 3; r++) {
          document.write("<TD>" + sales[m][r] + ",</TD>");   // 2-dimensional array
     }
     document.write("</TR>");
}
document.write("</TABLE>");

"Full" Demo     "Partial" Demo

This uses the nested for loops. The outer loop uses the variable m to step through all the months, writing the month names -- stored in the monthName Array -- in the first column. The inner loop uses the variable r to enter the data from the sales array into the appropriate rows.

          document.write("<TD>" + sales[m][r] + "</TD>");   // 2-dimensional array

This contains the expression sales[m][r], which represents the m'th element of the r'th element of sales. The double index ([m][r]) is how JavaScript accesses an element of an element. For example, where m = 0 and r = 2, JavaScript looks at the 1st Array stored in sales (the Jan Array), then looks at the 3rd element stored within that Array (180).