How to use the splice() method

How to use the splice() method

Written by Boyan Iliev on Jun 14th, 2021 Views Report Post

Introduction

Arrays will always be something that you will use or run into. You can store different types of data inside of them. For example - strings, numbers, objects, and even other arrays.

But what do you do when you want to remove a specific item. Well, you could delete the whole array and rewrite it, but that will be a waste of time. Luckily there is a method called splice to help you with that.

The splice Method

This method is super useful. It can change the contents of an array by removing or replacing existing elements and/or adding new ones. Let's create an array so that we can understand how this method works. Our array is going to be called superheroes.

let superheroes = ['Batman', 'Superman', 'Spider-man'];

Now let's add another item to our array.

Adding an Item

In order to add an item, we have to add assign our array to the method and then add a few parameters to our method. The first parameter is the index in which we want to add the new item. The second one tells the method that we want to add an item. So it has to be set to 0. And finally, the third one is the item itself. Here is how it should look:

superheroes.splice(1, 0, 'Daredevil');
-> ['Batman', 'Daredevil', 'Superman', 'Spider-man']

As you can see we added Daredevil to our array at the position of the index of 1. Remember that if you want to add an item the second parameter should always be 0

Now let's talk about how to remove an item.

Removing an Item

Removing an item works the same way as adding an item, but the second parameter should be set to 1. Now if you want to remove an item, first type the index of which that item is set and then type in 1.

superheroes.splice(3, 1);
-> ['Batman', 'Daredevil', 'Superman']

This is how you can remove the item, but what if you wanted to replace an item. You could write two lines of code. The first one removes the item and the second one adds the item to its position. But there is an easier way to do that with just one line of code.

Replacing an Item

Replacing an item is done exactly like removing an item, but you add a third parameter with the item that you want to be added to our array.

superheroes.splice(1, 1, 'The Flash')
-> ['Batman', 'The Flash', 'Superman']

We just replaced Daredevil with The Flash online with one line of code and with a single method.

Conclusion

As you can see the splice method is very easy to learn and use. It can really help you get used to changing your arrays.

I hope that this post has helped you. Any feedback would be greatly appreciated.

Comments (0)