What splice does
push adds an item at the end of an array and pop takes the last one away. To change an array anywhere else, use splice. It changes the array itself, in place.
The call splice(start, count, item) goes to index start, takes out count items there, and then puts in the items you list after count. Two forms cover most needs.
Insert: a count of 0
With a count of 0 nothing is taken out, so splice only inserts. The items from start onward move one place to the right:
let colors = ["red", "green", "blue"];
colors.splice(1, 0, "pink");
console.log(colors);
[ 'red', 'pink', 'green', 'blue' ]
Remove: a count of 1 and no items
With a count of 1 and nothing after it, splice only removes. The items behind the gap move one place to the left. It also returns an array of what it removed:
const gone = colors.splice(0, 1);
console.log(colors, gone);
[ 'pink', 'green', 'blue' ] [ 'red' ]
An insert returns an empty array, because it removed nothing.
The exercise, step by step
pets holds ["Rex", "Milo", "Luna"]. Bella has an appointment and goes second, at index 1. Then Milo goes home.
- Insert Bella. Call
pets.splice(1, 0, "Bella"). The array is nowRex, Bella, Milo, Luna, so the firstconsole.logprints 4. - Remove Milo. Milo used to be at index 1, but Bella pushed him to index 2. Call
pets.splice(2, 1).
The finished program:
let pets: string[] = ["Rex", "Milo", "Luna"];
pets.splice(1, 0, "Bella");
console.log(pets.length);
pets.splice(2, 1);
console.log(pets[0], pets[1], pets[2]);
It prints:
4
Rex Bella Luna
Traps
- Indexes change after every splice. Removing Milo at his old index 1 would take out Bella instead. Work out the new indexes, or do the removal first and the insertion second.
- The count is a number of items, not an end index.
splice(2, 1)removes one item, the one at index 2. - A nonzero count removes before it inserts.
["Rex", "Milo", "Luna"]aftersplice(1, 1, "Bella")is[ 'Rex', 'Bella', 'Luna' ]: Milo is replaced, not pushed along. - A negative start counts from the end.
splice(-1, 1)removes the last item. A start past the end just appends: on a 3-item array,splice(10, 0, "z")adds"z"at the end. - Don't confuse it with
slice.slicecopies a part and leaves the array alone, whilesplicechanges the array.
Following the indexes
Whenever you splice, keep a picture of the array after the call. Every item behind the spot has a new index, and the next call has to use the new one.
The order of the two calls matters because each one shifts the items behind it. Here is the array after each call in the exercise:
| After | pets |
|---|---|
| Start | Rex, Milo, Luna |
splice(1, 0, "Bella") | Rex, Bella, Milo, Luna |
splice(2, 1) | Rex, Bella, Luna |
If the removal used Milo's old index 1, it would take out Bella, and the array would be back to [ 'Rex', 'Milo', 'Luna' ]. The bug is easy to miss, because the program runs without any error.
Moving an item
Removing and inserting combine into a move. splice returns the removed items in an array, so the first item of that result is the one to put back somewhere else:
let moving = ["a", "b", "c", "d"];
const taken = moving.splice(2, 1);
moving.splice(0, 0, taken[0]);
console.log(moving);
[ 'c', 'a', 'b', 'd' ]
You can also insert several items in one call by listing them all after the count: splice(1, 0, "p", "q") on ["a", "b", "c"] gives [ 'a', 'p', 'q', 'b', 'c' ].
When you are not sure which index to use, print the array after each call while you work, then remove the extra prints. Seeing the real contents is quicker than reasoning about shifted positions in your head.
Key takeaways
splice(i, 0, x)insertsxat indexi.splice(i, 1)removes the item at indexi.- The array changes in place, and the items behind the spot get new indexes.
