Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
jsMultiDimensional Arrays [Go Back]
This page demonstrates how you can work with multidimensional arrays in javascript.

Predefined Multidimensional Array
A predefined multidimensional array is one that already has at least one set of data when the page loads. In this example, the predefined array has one index and several values associated with that index:
preDefinedArray = new Array();
preDefinedArray[0] = {value1:"predefined value 1", value2:"predefined value 2", value3:"predefined value 3"};


If you want to get "value1", all you need to do is reference it like:
var theValue = preDefinedArray[0].value1;
alert(theValue);


To see the call in action, click here.

You can assign a new value to "value1" as well. All you need to do is perform an assignment like:
var theValue = changedValue;
preDefinedArray[0].value1 = theValue;
alert(preDefinedArray[0].value1);


To see this process in action, enter a new value in the box below and click on the button:


Dynamically Defined Multidimensional Array
This type of multidimensional array is one that has not been defined. In this example, we need define the multidimensional array with values:
dynamicallyDefinedArray = new Array();
function multiDimensionalArrayConstructor(d1, d2, d3) {
this.value1 = d1;
this.value2 = d2;
this.value3 = d3;
}
function createArray(d1, d2, d3) {
dynamicallyDefinedArray[dynamicallyDefinedArray.length] = new multiDimensionalArrayConstructor(d1, d2, d3);
alert(dynamicallyDefinedArray[0].value1);
}


To see the call in action, click here. In the example above, the function "createArray()" is called with three arguments to create the multidimensional array at the current index value (starts out at 0) by referencing the function "multiDimensionalArrayConstructor()" which define the indices "value1", "value2" and "value3". Everytime the "createArray()" is called, it will create a new index with indices...this process is also required if you want to add an index of data to a predefined multidimensional array.

Sorting a multidimensional array alphabetically is as simple as calling a function you create to perform the sort:
function sortByValue1(a, b) {
var x = a.value1.toLowerCase();
var y = b.value1.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function performSort() {
dynamicallyDefinedArray.sort(sortByValue1);
}


As you can tell, the function "performSort()" sorts the array "dynamicallyDefinedArray" by calling the function "sortByValue1()". As with normal arrays, you can splice multidimensional arrays and much more in the same manner as normal arrays.
About Joe