## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 6.5. Inserting Elements in the Middle of an Array

## Problem

You want to insert elements in the middle of an array.

## Solution

Use the `splice( )` method.

## Discussion

You can use the `splice( )` method to insert elements as well as delete them. Any values passed as parameters to the `splice( )` method following the first and second parameters are inserted into the array starting at the index specified by the `start` parameter. All existing elements following that index are shifted to accommodate for the inserted values. If 0 is passed to the ```splice( )``` method for the `deleteCount` parameter, no elements are deleted, but the new values are inserted:

```myArray = ["a" ,"b", "c", "d"];

// Insert three string values--"one", "two", and "three"--starting at index 1.
myArray.splice(1, 0, "one", "two", "three");

// `myArray` now contains seven elements: "a", "one", "two", "three", "b", "c", and
// "d".
for (var i = 0; i < myArray.length; i++) {
trace(myArray[i]);
}```

You can also delete elements and insert new elements at the same time:

```myArray = ["a" ,"b", "c", "d"];

// Remove two elements and insert three more into `myArray` starting at index 1.
myArray.splice(1, 2, "one", "two", "three");

// `myArray` now contains five elements: "a", "one", "two", "three", and "d".
for (var i = 0; i < myArray.length; i++) {
trace(myArray[i]);
}```

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required