Chapter 4

Understanding Arrays

In This Chapter

arrow Identifying and defining arrays

arrow Building arrays

arrow Moving beyond 2D with multidimensional arrays

arrow Working within array elements

arrow Using array functions and properties

“I am large. I contain multitudes.”

— Walt Whitman

Arrays are a fundamental part of any programming language. In this chapter, you discover what they are, how to use them, and what makes JavaScript arrays distinct from arrays in other programming languages. You work with arrays to create lists, order lists, and add and remove items from lists.

ontheweb Don’t forget to visit the website to check out the online exercises relevant to this chapter!

Making a List

The earlier chapters in this book involve working with variables that are standalone pieces of data, such as: var myName = “Chris”, var firstNumber = “3”, and var how ManyTacos = 8. There are often times in programming (and in life) where you want to store related data under a single name. For example, consider the following types of lists:

  • A list of your favorite artists
  • A program that selects and displays a different quote from a list of quotes each time its run
  • A holiday card mailing list
  • A list of your top music albums of the year
  • A list of all your family and friends' birthdays
  • A shopping list
  • A to-do list
  • A list of New Year’s resolutions

Using single-value variables (see Chapter 3), you would need to create and keep track of multiple variables in order to accomplish any of these tasks. Here is an example of a list created using single-value variables:

var artist1 = "Alphonse Mucha";
var artist2 = "Chiara Bautista";
var artist3 = "Claude Monet";
var artist4 = "Sandro Botticelli";
var artist5 = "Andy Warhol";
var artist6 = "Wassily Kadinski";
var artist7 = "Vincent Van Gough";
var artist8 = "Paul Klee";
var artist9 = "William Blake";
var artist10 = "Egon Schiele";
var artist11 = "Salvador Dali";
var artist12 = "Paul Cezanne";
var artist13 = "Diego Rivera";
var artist14 = "Pablo Picasso";

This approach could work in the short term, but you’d quickly run into difficulties. For example, what if you wanted to sort the list alphabetically and move artists into the correct variable names based on their position in the alphabetical sort? You’d need to first move Mucha out of the artist1 variable (maybe into a temporary holding variable) and then move Bautista into the artist1 variable. The artist2 spot would then be free for Blake, but don’t forget that Mucha is still in that temporary slot! Blake’s removal from artist9 frees that up for you to move someone else into the temporary variable, and so on. Creating a list in this way quickly becomes complicated and confusing.

Fortunately, JavaScript (and every other programming language we know of) supports the creation of variables containing multiple values, called arrays.

Arrays are a way to store groups of related data inside of a single variable. With arrays, you can create lists containing any mix of string values, numbers, Boolean values, objects, functions, any other type of data, and even other arrays!

Array Fundamentals

An array consists of array elements. Array elements are made up of the array name and then an index number that is contained in square brackets. The individual value within an array is called an array element. Arrays use numbers (called the index numbers) to access those elements. The following example illustrates how arrays use index numbers to access elements:

myArray[0] = "yellow balloon";
myArray[1] = "red balloon";
myArray[2] = "blue balloon";
myArray[3] = "pink balloon";

In this example, the element with the index number of 0 has a value of "yellow balloon". The element with an index number 3 has a value of "pink balloon". Just as with any variable, you can give an array any name that complies with the rules of naming JavaScript variables. By assigning index numbers in arrays, JavaScript gives you the ability to make a single variable name hold a nearly unlimited list of values.

technicalstuff Just so you don't get too carried away, there actually is a limit to the number of elements that you can have in an array, although you're very unlikely to ever reach it. The limit is 4,294,967,295 elements.

In addition to naming requirements (which are the same for any type of variable, as described in chapter 3), arrays have a couple of other rules and special properties that you need to be familiar with:

  • Arrays are zero-indexed
  • Arrays can store any type of data

Arrays are zero indexed

JavaScript doesn't have fingers or toes. As such, it doesn't need to abide by our crazy human rules about starting counting at 1. The first element in a JavaScript array always has an index number of 0 (see Figure 4-1).

image

Figure 4-1: JavaScript is similar to a volume knob. It starts counting at zero!

What this means for you is that myArray[3] is actually the fourth element in the array.

Zero-based numbering is a frequent cause of bugs and confusion for those new to programming, but once you get used to it, it will become quite natural. You may even discover that there are benefits to it, such as the ability to turn your guitar amp up to the 11th level.

Arrays can store any type of data

Each element in an array can store any of the data types (see Chapter 3), as well as other arrays. Array elements can also contain functions and JavaScript objects (see Chapters 7 and 8).

While you can store any type of data in an array, you can also store elements that contain different types of data, together, within one array, as shown in Listing 4-1.

Listing 4-1: Storing Different Types of Data in an Array

item[0] = "apple";
item[1] = 4+8;
item[2] = 3;
item[3] = item[2] * item[1];

Creating Arrays

JavaScript provides in two different ways for you to create new arrays:

  • new keyword
  • Array literal notation

Using the new keyword method

The new keyword method uses new Array() to create an array and add values to it.

var catNames = new Array("Larry", "Fuzzball", "Mr. Furly");

You may see this method used in your career as a programmer, and it's a perfectly acceptable way to create an array.

warning Many JavaScript experts recommend against using this method, however. The biggest problem with using the new keyword is what happens when you forget to include it. Forgetting to use the new keyword can dramatically change the way your program operates.

Array literal

A much simpler and safer way to create arrays is to use what is called the array literal method of notation. This is what it looks like:

var dogNames =["Shaggy", "Tennesee", "Dr. Spock"];

That's all there is to it. The use of square brackets and no special keywords means that you’re less likely to accidentally leave something out. The array literal method also uses less characters than the new keyword method — and when you’re trying to keep your JavaScript as tidy as possible, every little bit helps!

Populating Arrays

You can add values to an array when it is first created, or you can simply create an array and then add elements to it at a later time. Adding elements to an array works exactly the same as creating or modifying a variable, except that you specify the index number of the element that you want to create or modify. Listing 4-2, shows an example of creating an empty array and then adding elements to it.

Listing 4-2: Populating an Empty Array

var peopleList =[];
peopleList[0] = "Chris Minnick";
peopleList[1] = "Eva Holland";
peopleList[2] = "Abraham Lincoln";

You don’t always need to add elements sequentially. It is perfectly legal in JavaScript to create a new element out of sequence. For example, in the preceding array, from Listing 4-2, you could add the following:

peopleList[99] = "Tina Turner";

Creating an array out of sequence like this effectively creates blank elements for all of the indexes in between peopleList[2] and peopleList[99].

So, if you check the length property of the peopleList array after adding an element with an index of 99, something interesting happens:

peopleList.length // returns 100

Even though you've only created four elements, JavaScript will say that the length of an array is 100 because the length is based on the highest numbered index, rather than on how many elements you've actually created.

Understanding Multidimensional Arrays

Not only can you store arrays inside of arrays, you can even put arrays inside of arrays inside of arrays. This can go on and on.

An array that contains an array is called a multidimensional array. To write a multidimensional array, you simply add more sets of square brackets to a variable name. For example:

var listOfLists[0][0];

Multidimensional arrays can be difficult to visualize when you first start working with them. Figure 4-2 shows a pictorial representation of a multidimensional array.

image

Figure 4-2: A pictorial representation of a multidimensional array.

You can also visualize multidimensional arrays as hierarchal lists or outlines. For example:

Top Albums by Genre

  1. Country

    1.1 Johnny Cash:Live at Folsom Prison

    1.2 Patsy Cline:Sentimentally Yours

    1.3 Hank Williams:I'm Blue Inside

  2. Rock

    2.1 T-Rex:Slider

    2.2 Nirvana:Nevermind

    2.3 Lou Reed:Transformer

  3. Punk

    3.1 Flipper:Generic

    3.2 The Dead Milkmen:Big Lizard in my Backyard

    3.3 Patti Smith:Easter

Here is a code that would create an array based on Figure 4-2:

var bestAlbumsByGenre = []
bestAlbumsByGenre[0] = "Country";
bestAlbumsByGenre[0][0] = "Johnny Cash:Live at Folsom Prison"
bestAlbumsByGenre[0][1] = "Patsy Cline:Sentimentally Yours";
bestAlbumsByGenre[0][2] = "Hank Williams:I'm Blue Inside";
bestAlbumsByGenre[1] = "Rock";
bestAlbumsByGenre[1][0] = "T-Rex:Slider";
bestAlbumsByGenre[1][1] = "Nirvana:Nevermind";
bestAlbumsByGenre[1][2] = "Lou Reed:Tranformer";
bestAlbumsByGenre[2] = "Punk";
bestAlbumsByGenre[2][0] = "Flipper:Generic";
bestAlbumsByGenre[2][1] = "The Dead Milkmen:Big Lizard in my Backyard";
bestAlbumsByGenre[2][2] = "Patti Smith:Easter";

Accessing Array Elements

You can access the elements of arrays in the same way that you set them, using square brackets and the index number. For example, to access the third element in any array called myArray, you would use the following:

myArray[2];

To access elements in a multidimensional array, just add more square brackets to get to the element you want:

bestAlbumsByGenre[0][1]; // returns "Patsy_Cline:Sentimentally Yours";

To test out setting and accessing the elements of an array, follow these steps:

  1. Open your Chrome browser and the open the JavaScript console.

    tip You can open your JavaScript Console using the Chrome menu or by pressing Command + Option + J on Mac or Ctrl + Shift + J in Windows.

  2. In the console, type the following statement, followed by the Return or Enter key, to create an array called lengthsOfString:

    var lengthsOfString = [2,4,1.5,80];

  3. Type the array name followed by the index number in square brackets to retrieve the value of each array element.

    For example:

    lengthsOfString[0];
    lengthsOfString[3];
    lengthsOfString[2];

  4. Enter an index number that doesn’t exist in the array.

    For example:

    lengthsOfString[4];

    Notice that the value of this array element is undefined.

  5. Type the following command to create a new variable to hold the total length of string that you have:

    var totalLength = lengthsOfString[0] + lengthsOfString[1] + lengthsOfString[2] + lengthsOfString[3];

  6. Finally, get the value of totalLength with this command:

    totalLength;

Looping through arrays

As you can imagine, working with multiple values of arrays by typing the array name and the index number can get tiring for your fingers after a while. Fortunately, there are easier ways to work with all of the elements in an array. The most common method is to use a programming construct called a loop. (We cover loops in much more detail in Chapter 6.)

It's also possible to work with multiple elements in an array by using JavaScript's built-in array functions.

Array properties

You can access certain data about an array by accessing array properties. The way to access array properties in JavaScript is by using dot notation. To use dot notation, you type the name of the array, followed by a period, followed by the property you want to access. (You can find out much more about properties in Chapter 8.) Table 4-1 lists all of the properties of JavaScript arrays.

Table 4-1 JavaScript's Array Properties

Property

Return Value

prototype

Allows the addition of properties and methods to an Array object

constructor

A reference to the function that created the Array object's prototype

length

Either returns or sets the number of elements in an array

The most commonly used array property is length. You have already seen the length property in action. Its purpose is to provide the number of elements in an array, whether defined or undefined. For example:

var myArray = [];
myArray[2000];
myArray.length; // returns 2001

You can also use the length property to truncate an array:

myArray.length;// returns 2001
myArray.length = 10;
myArray.length; // returns 10

Array methods

JavaScript array methods (also known as array functions) provide handy ways to manipulate and work with arrays. Table 4-2 shows a list of all the array methods along with descriptions of what they do or the values they produce.

Table 4-2 JavaScript Array Methods

Method

Return Value

concat()

A new array made up of the current array, joined with other array(s) and/or value(s)

every()

true if every element in the given array satisfies the provided testing function

filter()

A new array with all of the elements of a current array that test true by the given function

forEach()

Completes the function once for each element in the array

indexOf()

The first occurrence of the specified value within the array. Returns -1 if the value is not found

join()

Joins all the elements of an array into a string

lastIndexOf()

The last occurrence of the specified value within the array. Returns -1 if value is not found

map()

A new array with the result of a provided function on every element in the array

pop()

Removes the last element in an array

push()

Adds new items to the end of an array

reduce()

Reduces two values of an array to a single value by applying a function to them (from left to right)

reduceRight()

Reduces two values of an array to a single value by applying a function to them simultaneously (from right to left)

reverse()

Reverses the order of elements in an array

shift()

Removes the first element from an array and returns that element, resulting in a change in length of an array

slice()

Selects a portion of an array and returns it as a new array

some()

Returns true if one or more elements satisfy the provided testing function

sort()

Returns an array after the elements in an array are sorted (default sort order is alphabetical and ascending)

splice()

Returns a new array comprised of elements that were added or removed from a given array

toString()

Converts an array to a string

unShift()

Returns a new array with a new length by the addition of one or more elements

Using array methods

The syntax for using array methods differs depending on the particular method you are trying to use. You do, however, access the functionality of every array method the same way that you access array properties: by using dot notation.

technicalstuff For a complete reference to JavaScript array methods, with examples, visit https://docs.webplatform.org/wiki/javascript/Array#Methods.

Listing 4-3 shows some examples of the most commonly used JavaScript methods.

Listing 4-3: Commonly Used JavaScript Array Methods in Action

<html>
<head>
  <title>common array methods</title>
</head>
<body>
  <script>
    var animals = ["tiger" , "bear"];
    var fruit = ["cantaloupe" , "orange"];
    var dishes = ["plate" , "bowl" , "cup"];

    var fruitsAndAnimals = fruit.concat(animals);
    document.write (fruitsAndAnimals + "<br>");

    var whereIsTheTiger = animals.indexof("tiger";
    document.write ("The tiger has and index number of: " + whereIsTheTiger + "<br>");
  </script>
</body>
</html>

Figure 4-3 shows the result of Listing 4-3 when run in a browser.

image

Figure 4-3: Commonly used JavaScript array methods in action.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset