Working with multi-dimensional arrays

Arrays can be very useful to store as many or few values needed. Suppose we want to store information about cars. Specifically, assume we want to store following information pertaining to each car:

  • year the car was built
  • make

We could easily store this information with variables but this approach is not very efficient if we have many cars for which we want to store and retrieve data. If, for example, we have 7 cars for which we want to store data, we will need 14 (= 2 * 7) separate variables. Instead, we may use a multi-dimensional array store related information about cars.

A multi-dimensional array has two or more indexes for each element. For example, we can visualize a multi-dimensional with two elements as:

Index 0 1
0 2007 Toyota
1 2005 Honda

To declare this two-dimensional array, we can use the following JavaScript code:

<script language="javascript">
var twoDimArrCars = new Array();

twoDimArrCars [0] = new Array();
twoDimArrCars [0][0] = '2007';
twoDimArrCars [0][1] = 'Toyota';

twoDimArrCars [1] = new Array();
twoDimArrCars [1][0] = '2005';
twoDimArrCars [1][1] = 'Honda';

document.write ('twoDimArrCars [0][0] = ' + twoDimArrCars [0][0]);
document.write ('<br>twoDimArrCars [0][1] = ' + twoDimArrCars [0][1]);
document.write ('<br>twoDimArrCars [1][0] = ' + twoDimArrCars [1][0]);
document.write ('<br>twoDimArrCars [1][1] = ' + twoDimArrCars [1][1]);
</script>

In the above code, we start by declaring an array called twoDimArrCars. Next, the statement twoDimArrCars [0] = new Array(); allows us to use our array (specifically index 0 of our array) as a multi-dimensional array. This statement is necessary as JavaScript does not directly support multi-dimensional array. Essentially, we are creating our two dimensional array with arrays of arrays. Our next statement stores the value '2007' at twoDimArrCars [0][0]; similarly, the value 'Toyota' is stored at twoDimArrCars [0][1]. These two statements store those values into our two-dimensional array.

For the second index (or at index 1), we again create a new array with the statement twoDimArrCars [1] = new Array();. Next, we use this index to store values for each element in our array.

Finally, our last four statements print the values stored in the array. The following shows the output of our code: