Categories:
Partners

Creating a custom two-dimensional Array

With JavaScript's support for literal arrays in modern browsers (this tutorial predates that), this tutorial can arguably be considered obsolete. Nevertheless, we look at how to manually add additional dimensions to a regular array in JavaScript, and specifically, how to create a custom 2 dimensional array. If nothing it illustrates a technique for extending prebuilt JavaScript objects on your own.

Before we switch dimensions, lets first quickly review how to create "normal" arrays, and take it from there:

var myarray=new Array(3)

The above creates an array with 3 "storage compartments". Hopefully, this is old stuff to you. Graphically, it is represented as such:

array1.gif (2479 bytes)

A two-dimensional array is created simply by building on a "normal" array. Constructing a two-dimensional array requires that we declare another array on top of EACH of the "stems" (myarray[0], myarray[1]...).

Creating a two dimensional array

To start things off, lets first illustrate graphically how a two dimensional array is represented:

array2.gif (3737 bytes)

As you can see, to manually add a dimension to an array, what we need to do is  declare a new array on top of each individual array "stem". The translation of this idea to actual codes, as you will see, is actually very simple:

var myarray=new Array(3)
for (i=0; i <3; i++)
myarray[i]=new Array(3)

Is this simple or what? Well, it is. The key here is the for loop. By using a for loop, we incremented through the entire original array, declaring a new array at each "stop".

To access and store values into this "demented" array, just use double brackets:

myarray[0][0]="Compaq 486"
myarray[0][1]="Compaq 586"
myarray[0][2]="Compaq 686"
myarray[1][0]="Dell 486"
myarray[1][1]="Dell 586"
myarray[1][2]="Dell 686"
myarray[2][0]="IBM 486"
myarray[2][1]="IBM 586"
myarray[2][2]="IBM 686"

The trickest part of a two dimensional array may be keeping track of all the storage compartments in the array!

The two dimensional array above has  9 "storage compartments" (3*3).

Continuing on with our discussion, lets create a two dimensional array with 15 storage compartments:

var myarray=new Array(3)
for (i=0; i <3; i++)
myarray[i]=new Array(5)

If you know your multiplication, you know how to create arrays with any number of storage compartments!

Before we go any further, its appropriate to first discuss just when two dimensional arrays should be used over exiting variable declaration methods. A two dimensional array has a structure of a "tree", where multiple "sub variables" exist within a single "main variable":

array3.gif (3281 bytes)

"Compaq" here is the main variable that bonds together the sub variables (486,568 etc). You should use a two dimensional array only when you have a situation like the above, where sub grouping of a main  variable is necessary.