MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Arrays as objects

Arrays are objects, and have properties and methods like any other object. The prototype of the array object can be illustrated by the following figure:

Earlier this unit we dealt in detail with the length property of arrays. The first three methods of the Array object list above are discussed below. You are advised to consult on-line sources and books for details of the many other Array functions.

Array method: join

The join() method is a straightforward way of converting from the tabular, numerically indexed structure of an Array to a simple text String. join() copies all elements of an Array into a String object, separating each element value with the provided String argument, or with a comma "," if no argument is provided.

The general form of the join() method is:

    <array>.join( <separator> );
      

where <array> is a variable holding an array, and <separator> (if present) is a String to be used to separate each array element.

The join() method is called by default when an Array object is passed as a parameter to a document.write(...) statement.

An example of some code using the join( ) method is:

    var myArray = new Array( 4, 6, 7, 2);

    document.write("<p> myArray: " + myArray );
    document.write("<p> myArray.join(): " + myArray.join() );
    document.write('<p> myArray.join( " _ " ): ' + myArray.join( " _ " ) );
      

The output of the is code is

As can be seen from the output, calling document.write(...) with simply the Array variable as an argument is the same as providing the Array name and its default join() method. However, when the join() method is called with the argument " _ " this String is returned as the separator for each array element in the String returned by the method.

Array method: sort

As its name suggests, the sort() Array method provides a mechanism for changing the order of the elements of an Array according to provided criteria.

sort()'s default ordering is ascending, alphanumeric order. This produces some unintuitive results for numeric values:

        var myArray = new Array( 4, 16, 7, 2);

        document.write("<p> myArray: " + myArray );
        document.write("<p> myArray.sort(): " + myArray.sort() );
      

The browser output for the above is:

Since 16 comes alphabetically before 2 (1 is alphanumerically lower than 2 ), it appears first in the sorted array.

To sort array elements according to numerical (or some other) order an ordering function has to be provided as an argument to the sort() method. This ordering function must accept two arguments and return a numeric indication indicating which of the two arguments should occur before the other. If the function returns the value N, then:

  • N < 0: if the first argument should appear before the second.

  • N > 0: if the second argument should appear before the first.

  • N = 0: if the two arguments are equivalent.

An example of a function that places elements into ascending numeric order is:

        function smaller(n1, n2)
        {
        return (n1 - n2);
        }
      

The above function smaller() returns a negative value if the first argument is the smaller, zero if the two numbers are equal, and a positive number if the second argument is the smaller.

A more explicit (although less elegant) function, this time to return the larger of two numbers, can be written as follows:

        function larger(n1, n2)
        {
        if( n1 > n1)
          return -1; // "n1" first
        else if (n1 < n2)
          return 1; // "n2" first
        else
          return 0;
        }
      

As we can clearly see, this larger() function returns -1 if the first argument is larger, 1 if the second argument is larger, and zero if the arguments are the same. An example of some code that illustrates both the default (alphabetical) sorting, and sorting using the larger() function above, is as follows:

        var myArray = new Array( 4, 16, 7, 2);

        document.write("<p> myArray: " + myArray );
        document.write("<p> myArray.sort(): " + myArray.sort() );

        /////////////////////////////////////////////
        // function to return the smaller of 2 numbers
        /////// so will order numbers in DESCENDING order

        function larger(n1, n2)

        {
        if( n1 > n1)
          return -1; // "n1" first
        else if (n1 < n2)
          return 1; // "n2" first
        else
          return 0;
        }

        document.write("<p> myArray.sort(): " + myArray.sort(larger) );
      

The browser output from the above code is:

Array method: reverse

The reverse() method does not return any values; rather, it rearranges the Array elements into reverse order (i.e. reverse order of the numerical indices from 0..(length-1).

Consider an array myArray with the following values:

If the reverse() method is invoked on myArray, the following is obtained:

Some code to demonstrate this is as follows:

        var myArray = new Array(3);

        myArray[0] = "hello";
        myArray[1] = false;
        myArray[2] = 16;

        document.write("<p> myArray: " + myArray );

        myArray.reverse();

        document.write("<p> after reversing...");
        document.write("<p> myArray: " + myArray );
      

The browser output of the above code is:

Single and multi-dimensional arrays

The discussion of arrays have so far concerned what are known as single-dimension arrays, which are arrays forming an arrangements of values that can be accessed using a single numeric index, and can be pictured as a row of boxes, each box being numbered (by the index) and holding a value. Most programming languages provide facilities for multi-dimensional arrays, which are arrays requiring multiple numeric indices. A two dimensional array can be pictured as a book shelf, where each shelf is itself a single-dimension array.

In JavaScript, a two-dimensional array — holding months and the days of the month — can be created as follows:

        var delivery = new Array(12);

        delivery[0] = new Array(31); // January
        delivery[1] = new Array(29); // allow for Feb in leap years
        delivery[2] = new Array(31); // March...

        delivery[11] = new Array(31); // December
      

Notice that a two dimensional array is created by setting each element of an single-dimensional array to be arrays themselves.

This array could be used to represent the days on which a company could possibly perform a delivery, and wee could place true/false values into each element to indicate whether a delivery is possible on that day or not. If a delivery is not possible on the 1st or 2nd of January, but is possible on the third, we might write:

        delivery[0][0] = false; // no delivery possible 1st Jan
        delivery[0][1] = false; // no delivery possible 2nd Jan
        delivery[0][2] = true; // delivery is possible 3rd Jan
      

However, let us assume that due to poor climate and annual staff holidays that the company cannot perform deliveries during August. JavaScript's flexible nature allows us to do the following:

        delivery[7] = false; // August - no deliveries
      

Notice that a multi-dimensional array can easily have different sizes for its different rows, and some rows need not even be arrays at all.

To make working with multi-dimensional arrays easier, one can either add new methods to the Array prototype, or create new constructor functions which use Array as their prototype. Consider the following constructor function which attempts to make creating multi-dimensional arrays easier. It takes two arguments — the size of the first and second dimensions — and creates a two dimensional array:

        function two_dim_array(length_d1, length_d2)
        {

        // loop to make each element of "this" an
        // array with length "length_d2"

        var i = 0;
        while( i < length_d1 )
        {
        this[i] = new Array( length_d2 );
        i++;
        }

        // make the "length" property of array "this"
        // an object with properties
        // "d1" = "length_d1"
        // "d2" = "length_d2"

        this.length = { d1:length_d1, d2:length_d2 };
        }

	two_dim_array.prototype = Array;
	
        var myArray = new two_dim_array(3,2);