Team LiB   Previous Section   Next Section

9.2 Array Methods

In addition to the [] operator, arrays can be manipulated through various methods provided by the Array class. The following sections introduce these methods. Many of the methods were inspired in part by the Perl programming language; Perl programmers may find them comfortingly familiar. As usual, this is an overview only; complete details can be found in the core reference section of this book.

9.2.1 join( )

The Array.join( ) method converts all the elements of an array to strings and concatenates them. You can specify an optional string that is used to separate the elements in the resulting string. If no separator string is specified, a comma is used. For example, the following lines of code produce the string "1,2,3":

var a = [1, 2, 3];    // Create a new array with these three elements

var s = a.join(  );   // s == "1,2,3" 

The following invocation specifies the optional separator to produce a slightly different result:

s = a.join(", ");   // s == "1, 2, 3"

Notice the space after the comma. The Array.join( ) method is the inverse of the String.split( ) method, which creates an array by breaking up a string into pieces.

9.2.2 reverse( )

The Array.reverse( ) method reverses the order of the elements of an array and returns the reversed array. It does this in place -- in other words, it doesn't create a new array with the elements rearranged, but instead rearranges them in the already existing array. For example, the following code, which uses the reverse( ) and join( ) methods, produces the string "3,2,1":

var a = new Array(1,2,3);    // a[0] = 1, a[1] = 2, a[2] = 3

a.reverse(  );              // now a[0] = 3, a[1] = 2, a[2] = 1

var s = a.join(  );         // s == "3,2,1" 

9.2.3 sort( )

Array.sort( ) sorts the elements of an array in place and returns the sorted array. When sort( ) is called with no arguments, it sorts the array elements in alphabetical order (temporarily converting them to strings to perform the comparison, if necessary):

var a = new Array("banana", "cherry", "apple");

a.sort(  );

var s = a.join(", ");  // s == "apple, banana, cherry"  

If an array contains undefined elements, they are sorted to the end of the array.

To sort an array into some order other than alphabetical, you must pass a comparison function as an argument to sort( ). This function decides which of its two arguments should appear first in the sorted array. If the first argument should appear before the second, the comparison function should return a number less than zero. If the first argument should appear after the second in the sorted array, the function should return a number greater than zero. And if the two values are equivalent (i.e., if their order is irrelevant), the comparison function should return 0. So, for example, to sort array elements into numerical rather than alphabetical order, you might do this:

var a = [33, 4, 1111, 222];

a.sort(  );               // Alphabetical order:  1111, 222, 33, 4

a.sort(function(a,b) {    // Numerical order: 4, 33, 222, 1111

           return a-b;    // Returns < 0, 0, or > 0, depending on order


Note the convenient use of a function literal in this code. Since the comparison function is used only once, there is no need to give it a name.

As another example of sorting array items, you might perform a case-insensitive alphabetical sort on an array of strings by passing a comparison function that converts both of its arguments to lowercase (with the toLowerCase( ) method) before comparing them. You can probably think of other comparison functions that sort numbers into various esoteric orders: reverse numerical order, odd numbers before even numbers, etc. The possibilities become more interesting, of course, when the array elements you are comparing are objects, rather than simple types like numbers or strings.

9.2.4 concat( )

The Array.concat( ) method creates and returns a new array that contains the elements of the original array on which concat( ) was invoked, followed by each of the arguments to concat( ). If any of these arguments is itself an array, it is flattened and its elements are added to the returned array. Note, however, that concat( ) does not recursively flatten arrays of arrays. Here are some examples:

var a = [1,2,3];

a.concat(4, 5)          // Returns [1,2,3,4,5]

a.concat([4,5]);        // Returns [1,2,3,4,5]

a.concat([4,5],[6,7])   // Returns [1,2,3,4,5,6,7]

a.concat(4, [5,[6,7]])  // Returns [1,2,3,4,5,[6,7]] 

9.2.5 slice( )

The Array.slice( ) method returns a slice, or subarray, of the specified array. Its two arguments specify the start and end of the slice to be returned. The returned array contains the element specified by the first argument and all subsequent elements up to, but not including, the element specified by the second argument. If only one argument is specified, the returned array contains all elements from the start position to the end of the array. If either argument is negative, it specifies an array element relative to the last element in the array. An argument of -1, for example, specifies the last element in the array, and an argument of -3 specifies the third from last element of the array. Here are some examples:

var a = [1,2,3,4,5];

a.slice(0,3);    // Returns [1,2,3]

a.slice(3);      // Returns [4,5]

a.slice(1,-1);   // Returns [2,3,4]

a.slice(-3,-2);  // Returns [3] 

9.2.6 splice( )

The Array.splice( ) method is a general-purpose method for inserting or removing elements from an array. splice( ) modifies the array in place; it does not return a new array, as slice( ) and concat( ) do. Note that splice( ) and slice( ) have very similar names but perform substantially different operations.

splice( ) can delete elements from an array, insert new elements into an array, or perform both operations at the same time. Array elements that appear after the insertion or deletion are moved as necessary so that they remain contiguous with the rest of the array. The first argument to splice( ) specifies the array position at which the insertion and/or deletion is to begin. The second argument specifies the number of elements that should be deleted from (spliced out of ) the array. If this second argument is omitted, all array elements from the start element to the end of the array are removed. splice( ) returns an array of the deleted elements, or an empty array if no elements were deleted. For example:

var a = [1,2,3,4,5,6,7,8];

a.splice(4);    // Returns [5,6,7,8]; a is [1,2,3,4]

a.splice(1,2);  // Returns [2,3]; a is [1,4]

a.splice(1,1);  // Returns [4]; a is [1] 

The first two arguments to splice( ) specify which array elements are to be deleted. These arguments may be followed by any number of additional arguments that specify elements to be inserted into the array, starting at the position specified by the first argument. For example:

var a = [1,2,3,4,5];

a.splice(2,0,'a','b');  // Returns []; a is [1,2,'a','b',3,4,5]

a.splice(2,2,[1,2],3);  // Returns ['a','b']; a is [1,2,[1,2],3,3,4,5]

Note that, unlike concat( ), splice( ) does not flatten array arguments that it inserts. That is, if it is passed an array to insert, it inserts the array itself, not the elements of that array.

9.2.7 push( ) and pop( )

The push( ) and pop( ) methods allow us to work with arrays as if they were stacks. The push( ) method appends one or more new elements to the end of an array and returns the new length of the array.[2] The pop( ) method does the reverse: it deletes the last element of an array, decrements the array length, and returns the value that it removed. Note that both of these methods modify the array in place rather than producing a modified copy of the array. The combination of push( ) and pop( ) allows us to use a JavaScript array to implement a first in, last out stack. For example:

[2] In Netscape, when the language attribute of the <script> tag is explicitly set to "JavaScript1.2", push( ) returns the last value it appends to the array, rather than the new length of the array.

var stack = [];       // stack: []

stack.push(1,2);      // stack: [1,2]     Returns 2

stack.pop(  );        // stack: [1]       Returns 2

stack.push(3);        // stack: [1,3]     Returns 2

stack.pop(  );        // stack: [1]       Returns 3

stack.push([4,5]);    // stack: [1,[4,5]] Returns 2

stack.pop(  )         // stack: [1]       Returns [4,5]

stack.pop(  );        // stack: []        Returns 1 

9.2.8 unshift( ) and shift( )

The unshift( ) and shift( ) methods behave much like push( ) and pop( ), except that they insert and remove elements from the beginning of an array, rather than from the end. unshift( ) adds an element or elements to the beginning of the array, shifts the existing array elements up to higher indexes to make room, and returns the new length of the array. shift( ) removes and returns the first element of the array, shifting all subsequent elements down one place to occupy the newly vacant space at the start of the array. For example:

var a = [];            // a:[]

a.unshift(1);          // a:[1]         Returns: 1

a.unshift(22);         // a:[22,1]      Returns: 2

a.shift(  );           // a:[1]         Returns: 22

a.unshift(3,[4,5]);    // a:[3,[4,5],1] Returns: 3

a.shift(  );           // a:[[4,5],1]   Returns: 3

a.shift(  );           // a:[1]         Returns: [4,5]

a.shift(  );           // a:[]          Returns: 1 

Note the possibly surprising behavior of unshift( ) when it's invoked with multiple arguments. Instead of being inserted into the array one at a time, arguments are inserted all at once (as with the splice( ) method). This means that they appear in the resulting array in the same order in which they appeared in the argument list. Had the elements been inserted one at a time, their order would have been reversed.

9.2.9 toString( ) and toLocaleString( )

An array, like any JavaScript object, has a toString( ) method. For an array, this method converts each of its elements to a string (calling the toString( ) methods of its elements, if necessary) and outputs a comma-separated list of those strings. Note that the output does not include square brackets or any other sort of delimiter around the array value. For example:

[1,2,3].toString(  )          // Yields '1,2,3'

["a", "b", "c"].toString(  )  // Yields 'a,b,c'

[1, [2,'c']].toString(  )     // Yields '1,2,c'

Note that toString( ) returns the same string the join( ) method does when it is invoked with no arguments.[3]

[3] In Netscape, when the language attribute of the <script> tag is set to "JavaScript1.2", toString( ) behaves in a more complex way. In this case, it converts arrays to strings that include square brackets, and includes quotation marks around array elements that are strings, so that the resulting strings are valid array literal expressions.

toLocaleString( ) is the localized version of toString( ). It converts each array element to a string by calling the toLocaleString( ) method of the element, and then it concatenates the resulting strings using a locale-specific (and implementation-defined) separator string.

    Team LiB   Previous Section   Next Section