Table of Contents

11.8 Removing Elements from an Array

You can remove elements from an array by using the delete operator, reducing the length property of an array, or using one of the built-in array methods.

11.8.1 Removing Numbered Elements with the delete Operator

The delete operator sets an array element to undefined, using the following syntax:

delete arrayName[index]

where arrayName is any array and index is the number or name of the element we want to set to undefined. When used with numbered (not named) elements, the name delete is misleading, frankly. It does not remove a numbered element from the array; it merely sets the target element's value to undefined. A delete operation, therefore, is identical to assigning the undefined value to an element. We can verify this by checking the length property of an array after deleting one of its elements:

var myList = ["a", "b", "c"];
trace(myList.length);  // Displays: 3
delete myList[2];
trace(myList.length);  // Still displays 3...the element at index 2 is 
                       // undefined instead of "c", but it still exists

To truly delete elements, use splice( ) (to delete them from the middle of an array), or use shift( ) and pop( ) (to delete them from the beginning or end of an array). Note that delete behaves differently with named elements than with numbered elements. Using delete on named elements destroys them permanently, leaving no trace. As we saw in Chapter 5, delete can also destroy object properties as it does named array elements (in fact, named elements are actually object properties of the Array object).

11.8.2 Removing Elements with the length Property

Earlier we used the length property to add elements to an array. We can also set the array's length property to a number smaller than the current length in order to delete elements from the array (i.e., truncate the array):

var toppings = ["pepperoni", "tomatoes", "cheese", "green pepper", "broccoli"];
toppings.length = 3;
trace(toppings);  // Displays: "pepperoni,tomatoes,cheese"
                  // We trimmed elements 3 and 4 (the last two).

11.8.3 Removing Elements with Array Methods

Arrays come equipped with several built-in methods for removing elements. We've already seen how splice( ) can delete a series of elements from the middle of an array. The pop( ) and shift( ) methods are used to prune elements from the end or beginning of an array.

11.8.3.1 The pop( ) method

The pop( ) method is the antithesis of push( )�it removes the last element of an array. The syntax of pop( ) is simple:

arrayName.pop()

I don't know why, but I always think that "popping" an array is kinda funny. Anyway, pop( ) decrements the array's length by 1 and returns the value of the element it removed. For example:

x = [56, 57, 58];
trace(x.pop());  // Displays: 58 (the value of the popped element)
                  // x is now [56, 57]

As we saw earlier, pop( ) is often used in combination with push( ) to perform LIFO stack operations. In Example 11-4, we create a siteHistory array that tracks a user's navigation through a site. When the user navigates to a new frame, we add his location to the array using push( ). When the user navigates back, we pop( ) his last location off of siteHistory and send him to the preceding location. Example 11-4 can be downloaded from the online Code Depot.

Example 11-4. A Back button with history
// CODE ON FRAME 1 OF OUR MOVIE
stop( );
var siteHistory = new Array( );

function goto (theLabel) {
  // If we're not already at the requested frame...
  if (theLabel != siteHistory[siteHistory.length - 1]) {
    // ...add the request to the history, then go to the requested frame
    siteHistory.push(theLabel);
    this.gotoAndStop(siteHistory[siteHistory.length - 1]);
  }
  trace(siteHistory);
}

function goBack () {
  // Remove the last item in the history
  siteHistory.pop();
  // If there is anything left in the history...
  if (siteHistory.length > 0) {
    // ...go to the most recent frame
    this.gotoAndStop(siteHistory[siteHistory.length - 1]);
  } else {
    // ...otherwise go home
    this.gotoAndStop("home");
  }
  trace(siteHistory);
}

// NAVIGATION BUTTON
gallery_btn.onRelease = function ( ) {
  this._parent.goto("gallery");
}

// THE BACK BUTTON
back_btn.onRelease = function ( ) {
  this._parent.goBack();
}
11.8.3.2 The shift( ) method

Remember unshift( ), the method we used to add an element to the beginning of an array? Meet its alter ego, shift( ), which removes an element from the beginning of an array:

arrayName.shift()

Not as funny as pop. Oh well.

Like pop( ), shift( ) returns the value of the element it removes. The remaining elements all move up in the pecking order toward the beginning of the array. For example:

var sports = ["hackey sack", "snowboarding", "inline skating"];
trace(sports.shift( ));  // Displays: hackey sack
                        // sports is now ["snowboarding", "inline skating"]
trace(sports.shift( ));  // Displays: snowboarding
                        // sports is now ["inline skating"]

Because shift( ) truly deletes an element, it is more useful than delete for removing the first element of an array. We can also use shift( ) to limit the number of elements in a list. For example, suppose we're calculating the frame rate of a movie. We push( ) the current time onto an array after each frame renders. To limit the size of our array to the most recent 10 time samples, we shift( ) the oldest time off as necessary. To find the frame rate, we average the times in our array. Example 11-5 shows this technique.

Example 11-5. Calculating the frame rate of a movie
// Create a movie clip to track the frame rate
this.createEmptyMovieClip("fpsTracker", 1);
   
// Create our time measurement array in the fpsTracker movie clip
fpsTracker.elapsedTime = new Array();
   
// Use an onEnterFrame( ) event handler to measure the time after each frame
fpsTracker.onEnterFrame = function ( ) {
  // Add the current time to elapsedTime
  this.elapsedTime.push(getTimer( ));
   
  // If we have enough samples to calculate an average...
  if (this.elapsedTime.length > 10) {
    // ...remove the oldest time from elapsedTime
    this.elapsedTime.shift();
   
    // Average the number of elapsed milliseconds per frame
    this.elapsedAverage = (this.elapsedTime[this.elapsedTime.length - 1] - 
                           this.elapsedTime[0]) / this.elapsedTime.length;
   
    // To find the frames per second, divide 1 second by the elapsed average
    this.fps = 1000 / this.elapsedAverage;
    trace("Current fps " + this.fps);
  }
}
11.8.3.3 The splice( ) method

Earlier we saw that splice( ) can both remove elements from and add elements to an array. Since we've already looked at splice( ) in detail, we won't reexamine it here. However, given our current context, we should specifically demonstrate splice( )'s element-removal capabilities:

var x = ["a", "b", "c", "d", "e", "f"];
x.splice(1,3);  // Removes elements 1, 2, and 3, leaving ["a", "e", "f"]
x.splice(1);    // Removes elements 1 through the end leaving just ["a"] 

Table of Contents