DekGenius.com
[ Team LiB ] Previous Section Next Section

3.6 Combining Arrays

NN 4, IE 4

3.6.1 Problem

You want to blend two or more separate arrays into one larger array.

3.6.2 Solution

To join arrays together, use the concat( ) method of the array object, passing a reference to the other array as a parameter:

var comboArray = myArray.concat(anotherArray);

Arrays joined through the concat( ) method are not altered. Instead, the concat( ) method returns the combined array as a new value, which you can preserve in a separate variable. The base array (the one used to invoke the concat( ) method) comes first in the combined array.

For combining multiple arrays, pass the additional arrays as comma-delimited parameters to the concat( ) method:

var comboArray = myArray.concat(otherArray1, otherArray2, otherArray3);

The combined array has items in the same order as they appear in the comma-delimited arguments.

3.6.3 Discussion

The concat( ) method is not limited to tacking one array onto another. Comma-delimited parameters to the method can be any data type. A value of any data type other than an array becomes another entry in the main array—in the same sequence as the parameters. You can even combine arrays and other data types in the group of parameters passed to the method.

In addition to the concat( ) method, a quartet of array methods let you treat an array like a stack for tacking on and removing items from the front or backends of the array. The push( ) method lets you append one or more items to the end of an array; the corresponding pop( ) method removes the last item from the array and returns its value. You can perform the same operations at the beginning of the array with the unshift( ) (append) and shift( ) (remove) methods. All four of these methods are implemented in NN 4 or later and IE 5.5 or later for Windows.

3.6.4 See Also

Recipe 3.5 for sorting an array—something you may wish to do once you add to an array; Recipe 3.7 for dividing an array.

    [ Team LiB ] Previous Section Next Section