Arrays

We've seen that variables can hold numbers, strings, and references to objects. There's one more kind of information that JavaScript understands: Arrays. Arrays are lists. You might have a list of URLs that you want to visit, a list of names that you want to remember, or a list of colors in which you'd like text displayed. All these lists can be stored in Arrays. Arrays are ordered collections of values referred to by a single variable name. Starting with JavaScript 1.1 there is a built-in Array Object ready for you to use.

colors[0] = "red"
colors[1] = "blue"
colors[2] = "green"

An Array is a collection of data values, just as an object is. While each data value contained in an Object has a name, each data value in an Array has a number, or index. Array elements are referred to by their indexes – the number in the brackets. In JavaScript, Arrays start with index zero.

Arrays may contain ANY type of JavaScript data, including references to other Arrays or to Objects or Functions. For example:

document.images[1].width

This code refers to the width property of an object stored in the second element of an Array stored in the images property of the document Object.

Note that the Arrays describe here differ from the Associative Arrays. Associative Arrays are indexed by strings. JavaScript does not support Multi-Dimensional Arrays, except as Arrays of Arrays. (See the section below) NOTE: This will be also covered next week.

Arrays in JavaScript are created using the Array() constructor Object. You can create an Array of undefined length by using the new keyword which is used to create an instance of an Object:

var ArrayName = new Array();

So we've created a variable called ArrayName, and we've used new Array() to make ArrayName an instance of an Array Object. Then we could begin placing data into the Array in the way we did above. The length of the Array changes dynamically as you assign values to the Array. The length of the Array is defined by the largest index number used.

var sampleArray = new Array();
sampleArray[24] = "25th Element";

creates an Array with 25 elements. (Remember - indexes start at zero.)

It is also possible to define an initial length of an Array by passing the length of the Array() Object as an argument:

var sampleArray = new Array(100);

In addition, you can create an Array and assign values to all its elements at the time it is defined. Here's how to create an Array of colors:

var colors = new Array("red", "blue", "green");

// creates a 3-element Array
colors[0] == "red"
colors[1] == "blue"
colors[2] == "green"

NOTE: colors.length is equal to 3

Create your own Array

Now that you have an Array, what can you do with it? The good thing about Arrays is that elements of an Array can be accessed by number. The first element is number 0 and can be accessed like this:

var the_element = colors[0];

After you execute this line of JavaScript, the variable the_element will hold the string "red." As you can see, you access the first element of an Array by writing the name of the Array and putting the element's number in square brackets. The second element of an Array is number 1.

Once you've created an Array, you can add to and change its values. If you decided to change the first element of the colors Array to purple instead of red, you could write this:

colors[0] = "purple";

Arrays are often used in tandem with loops.

There's another way to store data in Array Objects. Instead of numbers, you can use string values in place of the index number (the subscripts, as they're often known). For example, you can write this:

var house = new Array(0);

house["color"] = "white";
house["style"] = "ranch";
house["bedrooms"] = 3;
house["baths"] = 2;

Note that this time we declared the Array to have a length of 0. Then created several elements, but instead of using index numbers we used index "names": house["color"] instead of house[0], for example.

This can be handy in some situations, and it will work fine, with one major difference. Elements with string indices are stored differently from those with numeric indices. They actually become properties of the object; so house["color"] is equivalent to house.color in the above example. In fact, the house Array still has a length of 0 even after stored data in it. Properties are really not elements of an Array, even though they can be referenced with square brackets. The Array will appear to have no length, but it's still storing data for you.

Array Properties

length

An integer specifying the number of of elements in the Array, or when the Array does not have contiguous elements a number one larger than the index of the last element in the Array.

var a = new Array(1, 2, 3, "testing");
var getLength = a.length; // length = 4

Array Methods

The Array object possesses 3 Methods, each of which enables you to manipulate the elements in the Array. Each Method is fairly straightforward, so let’s take a moment to consider each.

join()

returns all the elements of the Array together as a single string. This takes one argument: a string used as the separator between each element of the Array in the final string. If the argument is omitted, join() uses a comma-space as the separator

var a = new Array(1, 2, 3, "testing");

var s = a.join("+");  // s is the string == "1+2+3+testing"
var s1 = a.join();  // s1 is the string == "1,2,3,testing"
var s2 = a.join(" ");  // s2 is the string == "1 2 3 testing"
var s3 = a.join("-");  // s3 is the string == "1-2-3-testing"

reverse()

This one’s a no-brainer. Simply, calling the reverse() Method for an Array will reverse the positions of each element. Suppose you have this four-element Arrays named classes & numbers:

classes[0] = “Freshman”;
classes[1] = “Sophomore”;
classes[2] = “Junior”;
classes[3] = “Senior”;

numbers[0] = 59;
numbers[1] = 100;
numbers[2] = 4000;
numbers[3] = 5;

You can call the reverse() Method in this way:

classes.reverse();
numbers.reverse();

As a result, the Arrays would look like this:

classes[0] == “Senior”
classes[1] == “Junior”
classes[2] == “Sophomore”
classes[3] == “Freshman”

numbers[0] == 5
numbers[1] == 4000
numbers[2] == 100
numbers[3] == 59

sort()

This Method, as its name implies, can be used to sort the elements in an Array. Instead of simply reversing them, as the reverse() Method does, the sort() Method re-orders the elements in the Array based upon certain sorting criteria.

The simplest usage of the sort() Method is as follows, using the same original classes Array from the previous example:

classes.sort();
numbers.sort();

The above expression will sort the Array’s elements alphabetically. If an element in the Array is a number, it is also sorted alphabetically (e.g. “500” comes before “95”). The resulting element sequence would look like this:

classes[0] == “Freshman”
classes[1] == “Junior”
classes[2] == “Senior”
classes[3] == “Sophomore”

numbers[0] == 100
numbers[1] == 4000
numbers[2] == 5
numbers[3] == 59

Two-Dimensional Array

In and of itself, the Array is a simple concept. This is partially because the basic Array is one-dimensional: its elements are indexed only as 0, 1, 2, 3, and so on. One way to increase the flexibility of an Array is to build it two-dimensionally.

In a two-dimensional Array, each element may also be an Array in its own right. Thus, each element in an Array can be an Array with its own elements. Confusing? It takes some re-reading to get the mental hang of it. Recall a basic Array declaration:

 cars = new Array();

As usual, then, you could say this:

cars[0] = “Toyota”;

The above is a typical one-dimensional Array. Suppose, though, that you’d like to store the types of Toyota models within the cars Array. Instead of assigning a string value (such as “Toyota”) to cars[0], you can assign a new Array!

cars[0] = new Array();

Now cars[0] is its own Array, with a set of elements. Next, assign the automobile make to index 0 of cars[0] and assign each model name to succeeding elements:

cars[0][0] = ”Toyota”;
cars[0][1] = ”Camry”;
cars[0][2] = ”Celica”;
cars[0][3] = ”4Runner”;

Moving along, you can add another make and other models to your cars Array:

cars[1][0] = ”Ford”;
cars[1][1] =”Mustang”;
cars[1][2] = ”Taurus”;

What you’ve done is create an Array within an Array! This tends to cause some people’s brains to hurt at first glance, but it just takes some practice.

A "real" Multi-Dimensional Array example will be covered later on.