Start learning free

LESSON 114 OF 675 · ARRAYS I

Insert and Remove at a Position in TypeScript with splice

Lesson Read the full explanation

TL ; DR:

splice(i, 0, x) puts x at index i. Use splice(i, 1) to take out the item at index i. The other items move to make room or to close the gap.


let colors = ["red", "green", "blue"];

colors.splice(1, 0, "pink");
// colors is now ["red", "pink", "green", "blue"]

colors.splice(0, 1);
// colors is now ["pink", "green", "blue"]


Full lesson:

push adds an item at the end, and pop takes the last one away. To work anywhere else in an array, use splice.

splice(start, count, item) goes to index start. It takes out count items there. Then it puts in the items you list after count.

With a count of 0, it only inserts. The items from start on move one place to the right:

let pets = ["Rex", "Milo"];

pets.splice(0, 0, "Luna");
// pets is now ["Luna", "Rex", "Milo"]

With a count of 1 and no items, it only removes. The items after it move one place to the left:

pets.splice(0, 1);
// pets is now ["Rex", "Milo"]

Watch the indexes. After an insert or a removal, the items behind that spot have new indexes.

splice changes the array itself. It returns an array of the removed items, like ["Luna"].


Your task

pets holds the pets waiting at the vet, in order.

Bella has an appointment, so she goes second, at index 1. Then Milo goes home. Take him out of the line.

The code below prints how many pets wait once Bella is in. At the end, it prints the pets left.

Expected output:

4
Rex Bella Luna
STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · ARRAYS I

    Array Insert Remove in TypeScript, explained

    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.

    1. Insert Bella. Call pets.splice(1, 0, "Bella"). The array is now Rex, Bella, Milo, Luna, so the first console.log prints 4.
    2. 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"] after splice(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. slice copies a part and leaves the array alone, while splice changes 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:

    Afterpets
    StartRex, 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) inserts x at index i.
    • splice(i, 1) removes the item at index i.
    • The array changes in place, and the items behind the spot get new indexes.
    Keep going with TypeScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free