How to Insert an Item in the Middle of an Array?

How to Insert an Item in the Middle of an Array?

ยท

2 min read

How do we insert an item to where the yellow arrow is?

We can easily insert items at the start (unshift) and end (push) of an array.

But, what about the middle? ๐Ÿค”

Ta-da! splice!

splice is a method that allows you to insert and delete items in an array.

It takes three arguments:

  1. The index you want to start your operation

  2. The number of items you wish to delete (optional)

  3. The list of items you wish to insert (optional)

Let's go over some examples.

Inserting a Single Item

Let's correct the array we showed at the beginning.

const array = ['a', 'b', 'c', 'e', 'f', 'g'];
array.splice(3, 0, 'd');
console.log(array)

So, what happens is this:

  1. We walk to index 3, which is pointing to the element e

  2. We delete 0 items

  3. Then we insert d at index 3, effectively shifting e

Inserting Multiple items

const array = ['a', 'b', 'c', 'd', 'h', 'i', 'j', 'k'];
array.splice(4, 0, 'e', 'f', 'g');
console.log(array)

So, a breakdown of what happens is:

  1. We walk to index 4, which is pointing to the element h

  2. We delete 0 items (again)

  3. Then we insert e, f and g at index 4 (putting them in the correct place)

Bonus: Inserting and Deleting

Now, you might be wondering... (or not)

How does the delete part work?

const array = ['Apple', 'Banana', 'Orange', 'Mandarin', 'Blueberry'];
array.splice(2, 2, 'Raspberry');
console.log(array)

It's similar to what happened before:

  1. We walk to index 2, which is pointing to the element Orange

  2. We delete 2 items (Orange and Mandarin)

  3. Then we insert Raspberry at index 2

Bonus: Bonus

An interesting behavior happens if you omit the number of items to delete.

const array = ['a', 'b', 'c', 'd', 'h', 'i', 'j', 'k'];
array.splice(1);
console.log(array)

Here's what happens:

  1. We walk to index 1, which is pointing to the element b

  2. We delete all items from that point onwards

  3. Then we insert nothing

Leaving us with just one element.

From mdn:

If deleteCount is omitted, or if its value is greater than or equal to the number of elements after the position specified by start, then all the elements from start to the end of the array will be deleted.

splice is a pretty interesting and versatile method.

What applications have you found for it?

Thanks for reading. ๐Ÿ™‚.

ย