JavaScript EditorFree JavaScript Editor     DHTML Editor 

Main Page Previous Section Next Section

3.7 Dividing Arrays

NN 4, IE 5.5(Win)

3.7.1 Problem

You want to divide one array into two or more array segments.

3.7.2 Solution

To divide an array into two pieces, use the splice( ) method on the original array (the method is available in NN 4 or later and IE 5.5 or later for Windows). The splice( ) method requires two parameters that signify the zero-based index of the first item, and the number of items from there to be removed from the original array. For example, consider the following starting array:

var myArray = [10, 20, 30, 40, 50, 60, 70];

To create two arrays that have three and four items, respectively, first decide which items are to remain in the original array. For this example, we'll remove the first three items to their own array:

var subArray = myArray.splice(0, 3);

After the splice( ) method executes, there are now two arrays as follows:

myArray = [40, 50, 60, 70]
subArray = [10, 20, 30]

You can extract any sequence of contiguous items from the original array. After the extraction, the original array collapses to its most compact size, reducing its length to the number of items remaining. The two arrays do not maintain any connection with each other after the splice( ) method executes.

3.7.3 Discussion

The splice( ) method does more than merely cut out a group of entries from an array. Optional parameters to the method let you both remove and insert items in their place all in one step. Moreover, you don't have to replace removed items with the same quantity of new items. To demonstrate, we'll start with a simple array:

var myArray = [10, 20, 30, 40, 50, 60, 70];

Our goal is to extract the middle three items (preserved as their own array for use elsewhere), and replace these items with two new items:

var subArray = myArray.splice(2, 3, "Jane", "Joe");

After the splice( ) statement executes, the two arrays have the following content:

myArray: [10, 20, "Jane", "Joe", 60, 70]
subArray: [30, 40, 50]

Using the splice( ) method is the best way to delete entries from within an array. If you simply invoke the method without capturing the returned result, the items specified by attributes are gone, and the length of the array closes up to the remaining items.

One other array method, slice( ), allows you to copy a contiguous section of an array and create a separate, new array with those entries. The difference between slice( ) and splice( ) is that slice( ) does not alter the original array. Parameters to slice( ) are integers of the starting index of the group to extract and the ending index. (Or else, omit the ending index to take every entry to the end of the array.)

3.7.4 See Also

Recipe 3.6 for combining two or more arrays into a single array.

    Main Page Previous Section Next Section
    Предлагаем столешницы

    JavaScript EditorJavaScript Checker     DHTML Editor