3.2 Creating a Multidimensional Array

NN 3, IE 4

3.2.1 Problem

You want to consolidate data in an array construction of two dimensionssuch as a tableor even more dimensions.

3.2.2 Solution

Create an array of arrays. As an example, consider the following small table of regional sales data:





















To place the data portions of this table into an array that has three items (one for each region row), in which each item contains an array of four nested items (sales figures for each quarter column for that region), you can use a variety of array-creation syntaxes. A comparatively long version creates each of the nested arrays first, and then assigns those nested arrays to the outer array:

var eastArray = new Array(2300, 3105, 2909, 4800);
var centralArray = new Array(1800, 1940, 2470, 4350);
var westArray = new Array(900, 1200, 1923, 3810);
var salesArray = new Array(eastArray, centralArray, westArray);

The most compact array creation approach is to use the bracket shortcuts exclusively:

var salesArray = [[2300, 3105, 2909, 4800], 
                  [1800, 1940, 2470, 4350], 
                  [900, 1200, 1923, 3810]];

To access any nested item within salesArray, use a double index. For example, to reach the first item (East Q1), the reference is:


There are no commas or other symbols allowed between the bracketed index values in this kind of reference. The first index applies to the first-level array, while the second applies to the nested arrays. Therefore, to reach the Central region's Q3 sales, the reference is:


You may read and write to these multidimensional array items just like any other array items.

3.2.3 Discussion

There is no practical limit to the number of nesting levels you can create for a multidimensional array. For each dimension, lengthen the reference to the most deeply nested items with another bracketed index value. See Recipe 3.4 for using loops to inspect every item in a deeply nested array.

One potential problem with using a multidimensional array is that you may lose track of what a particular entry represents. When you look at the array creation examples just shown, the numbers lose their contextual meaning with respect to region or quarter. Their position in the two-dimensional array is all that the numbers know about. It is up to the rest of your scripts to keep the relationships between the data points and their meanings straight. In many cases, you may be better served by creating an array of custom objects. The objects can contain properties that provide labels and context for the raw data. See Recipe 3.8 and Recipe 3.9 for additional thoughts on the issue.

3.2.4 See Also

Recipe 3.4 to see how to iterate through simple and multidimensional arrays; Recipe 3.8 for using an array of objects in place of a multidimensional array; Recipe 3.9 for a custom object implementation of the sales example and how to create a simulated hash table to speed access to a particular entry.