14. Arrays


In This Chapter

Use arrays to handle lists of data

Learn how to perform common tasks using the various Array properties


Let’s imagine you are jotting down a list on a piece of paper. Let’s call the piece of paper “groceries.” Now, on this sheet of paper, you write a numbered list starting with zero with all the items that belong there such as what you see in Figure 14.1.

Image

FIGURE 14.1 An example of a grocery list.

By simply creating a list of things, what you have right now is a real-world example of an array! The piece of paper called “groceries” would be your array. The items that you need to purchase are known as array values (or array elements).

In this chapter, you will learn all about what I like to go grocery shopping for. You may indirectly get an introduction to the very common built-in type, the array.

Onwards!

Creating an Array

The popular way in which all the cool kids create arrays these days is to use an open and close bracket. The example that follows is our groceries variable that is initialized to an empty array:

var groceries = [];

You have your variable name on the left, and you have a pair of brackets on the right that initializes this variable as an empty array. This bracket-y approach for creating an array is better known as the array literal notation.

Now, you will commonly want to create an array with some items inside it from the very beginning. To create these non-empty arrays, place the items you want inside the brackets and separate them by commas:

var groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami",
  "Juice"];

Notice that my groceries array now contains Milk, Eggs, Frosted Flakes, Salami, and Juice. I just have to reiterate how important the commas are. Without the commas, you’ll just have one giant item. All right, now that you’ve learned how to declare an array, let’s look at how you can actually use it to store and work with data.

Accessing Array Values

One of the nice things about arrays is that you not only have easy access to the array, but you also have easy access to the array values...similar to highlighting an item on your grocery list as shown in Figure 14.2.

Image

FIGURE 14.2 Eggs are highlighted. Must be important.

The only thing you need to know is the procedure for accessing an individual item.

Inside an array, each item is assigned a number (formally known as an index value) starting with zero just like you saw with characters inside a string earlier. In the above example, Milk would have an index value of 0, Eggs would have an index value of 1, Frosted Flakes the index value of 2, and so on.

Let’s say that our groceries array is declared as follows:

var groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami",
  "Juice"];

If I wanted to access an item from the array, all I need to do is specify the index value of the item I am interested in:

groceries[1];

The index value is specified using square brackets. In this example, you are referring to the Eggs value because the index value 1 refers to it. If you specified a 2, you would return Frosted Flakes. You can keep specifying a larger index value until you have no more entries in the array left that map to it.

The number you can use as your index value goes all the way from 0 to one less than your array’s length. The reason is that, as shown in the diagram earlier, your index values start with a value of 0. If your array only has 5 items, trying to display grocery[6] or grocery[5] will result in a message of undefined.

Let’s go one step further. In most real-world scenarios, you will want to programmatically go through your array as opposed to accessing each item individually.

You can take what I explained in the previous paragraph and use a for loop to accomplish this:

for (var i = 0; i < groceries.length; i++) {
    var item = groceries[i];
}

Notice the range of your loop starts at 0 and ends just one before your array’s full length (as returned by the length property). This works because, like I mentioned earlier, your array index values go from 0 to one short of the value returned for the array’s length. And yes, the length property returns a count of all the items in your array! (To be precise, the length property returns the number of index values in your array, and that can sometimes not equal the number of actual items your array is storing. That is a nitpicky detail we’ll deal with another time.)

Adding Items to Your Array

Rarely will you leave your array in the state you initialized it in originally. You will want to add items to it. To add items to your array, you will use the push method:

groceries.push("Cookies");

The push method is called directly on your array, and you pass in the data you want to add to it. By using the push method, your newly added data will always find itself at the end of the array.

For example, after running the code on our initial array, you will see Cookies added to the end of your groceries array as shown in Figure 14.3.

Image

FIGURE 14.3 Our newly added item was placed at the end.

If you want to add data to the beginning of your array, you use the unshift method:

groceries.unshift("Bananas");

When data is added to the beginning of your array, the index value for all of the existing items increases to account for the newly inserted data as shown in Figure 14.4.

Image

FIGURE 14.4 This time, our newly added item was placed at the beginning.

The reason is that the first item in your array will always have an index value of 0. This means that the space originally occupied by the zeroth item needs to push itself and everything below it out to make room for the new data.

Both the push and unshift methods, besides adding the elements to the array when you use them, return the new length of the array as well:

alert(groceries.push("Cookies")); // returns 6

Not sure why that is useful, but keep it under your hat in case you do need it.

Removing Items from the Array

To remove an item from the array, you can use the pop or shift methods. The pop method removes the last item from the array and returns it:

var lastItem = groceries.pop();

The shift method does the same thing on the opposite end of the array. Instead of the last item being removed and returned, the shift method removes and returns the first item from the array:

var firstItem = groceries.shift();

When an item is removed from the beginning of the array, the index position of all remaining elements is decremented by 1 to fill in the gap:

Image

Note that, when you are adding items to your array using unshift or push, the returned value from that method call is the new length of your array. That is not what happens when you call the pop and shift methods, though! When you are removing items using shift and pop, the value returned by the method call is the removed item itself!

We are almost done talking about removing things. The last method we are going to look at is slice:

var newArray = groceries.slice(1, 4);

The slice method allows you copy a portion of an array and return a new array with just those copied items. In this snippet, we copy all items between the second and fifth items in our array and return them to a new array we call...newArray! When you are using slice, your original array is never modified. No items are actually removed. They are simply copied over.

Finding Items in the Array

To find items inside your array, you have two built-in methods called indexOf and lastIndexOf. These methods work by scanning your array and returning the index position of the matching element.

The indexOf method returns the index value of the first occurrence of the item you are searching for:

var groceries = ["milk", "eggs", "frosted flakes", "salami",
  "juice"];
var resultIndex = groceries.indexOf("eggs", 0);

alert(resultIndex); // 1

Notice that the resultIndex variable stores the result of calling indexOf on our groceries array. To use indexOf, I pass in the element I am looking for along with the index position to start from:

groceries.indexOf("eggs", 0);

The value returned by indexOf in this case will be 1.

The lastIndexOf method is similar to indexOf in how you use it, but it differs a bit on what it returns when an element is found. Where indexOf finds the first occurrence of the element you are searching for, lastIndexOf finds the last occurrence of the element you are searching for and returns that element’s index position.

When you search for an element that does not exist in your array, both indexOf and lastIndexOf return a value of −1.

Merging Arrays

The last thing we are going to do is look at how to create a new array that is made up of two separate arrays. Let’s say you have two arrays called good and bad:

var good = ["Mario", "Luigi", "Kirby", "Yoshi"];
var bad = ["Bowser", "Koopa Troopa", "Goomba"];

To combine both of these arrays into one array, use the concat method on the array you want to make bigger and pass the array you want to merge into it as the argument. What will get returned is a new array whose contents are both good and bad:

var goodAndBad = good.concat(bad);
alert(goodAndBad);

In this example, because the concat method returns a new array, the goodAndBad variable ends up becoming an array that stores the results of our concatenation operation. The order of the elements inside goodAndBad is good first and bad second:

Image

Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


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

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