JavaScript Array type provides a very powerful splice() method that allows you to insert new elements into the middle of an array. However, you can use this method to delete and replace existing elements as well.
Also Read: JavaScript Slice Method – Practical Examples
In this tutorial, you will learn how you can remove, add, or replace elements of an array using the splice() method.
JavaScript Splice( ) Method
The splice()
method modifies an array (adds, removes or replaces elements).
The splice() method modifies an array (adds, removes or replaces elements).
Syntax:
arr.splice(start, deleteCount, item1, ..., itemN)
Here, arr
is an array.
start
– The index from where the array is changed.deleteCount
(optional) – The number of items to remove from start.item1
, …,itemN
(optional) – The elements to add to the start index. If not specified, splice() will only remove elements from the array.
For example:
In this example, we have an array of food items.
const food = ['pizza', 'cake', 'salad', 'cookie'];
If we want to add another food item to the array at index 1, then we can use the following code:
food.splice(1,0,"burrito")
The first number is the starting index, and the second number is the delete count. Since we are not deleting any items, our delete count is zero.
This is what the result would look like in the console.
const food = ['pizza', 'cake', 'salad', 'cookie']; food.splice(1,0,"burrito") console.log(food); //[ 'pizza', 'burrito', 'cake', 'salad', 'cookie' ]
If we console.log(food.splice(1,0,"burrito"))
, then we would get back an empty array because nothing was removed from our array.
const food = ['pizza', 'cake', 'salad', 'cookie']; food.splice(1,0,"burrito") console.log(food.splice(1,0,"burrito")); //[]
In this next example, we want to remove “salad” from the array. We can use the start and delete parameters to accomplish this.
food.splice(2,1);
The number 2 is the start position and the number 1 represents the delete count. Since salad is at index 2 then it will be removed from the array.
This is what our array looks like now:
const food = ['pizza', 'cake', 'salad', 'cookie']; food.splice(2,1); console.log(food); //[ 'pizza', 'cake', 'cookie' ]
Use Cases
Now that we have understood what the parameters are and have seen one sample example. Let’s now try to see few more use cases and examples of how this can be implemented when writing our program.
Deleting Zero Elements Before a Specified Index
If we want to add an element without removing any item, we simply specify the index, and it would remove nothing but start before the specified index.
Let’s have a look at the example below:
const myMusic = ['piano', 'guitar', 'violin', 'orchestra']; const removedElement = myMusic.splice(2, 0, 'drum'); console.log(myMusic); //[ 'piano', 'guitar', 'drum', 'violin', 'orchestra' ] console.log(removedElement); //[] , no elements deleted
In the preceding code, we try to remove an element on index 3, meaning as soon as it gets to index 3 whatever items it finds would be deleted without replacing it with any element.
const myMusic = ['piano', 'guitar', 'drum', 'violin', 'orchestra'] myMusic.splice(3, 1); console.log(myMusic); //[ 'piano', 'guitar', 'drum', 'orchestra' ]
We can also delete one element and add other elements.
const myMusic = ['piano', 'guitar', 'drum', 'violin', 'orchestra'] const removedElement = myMusic.splice(3, 1, 'sax'); console.log(myMusic); //[ 'piano', 'guitar', 'drum', 'orchestra' ] console.log(removedElement); //removedElement is - [ 'violin' ]
Similarly, as soon as we got to index 3, whatever it finds, in this case, ‘violin’, would be deleted, and add newer ones (‘sax’).
Deleting One or More Elements at a Specified Index
Suppose we want to remove two items without adding a new one into the array then the code will be:
const myMusic = ['piano', 'guitar', 'drum', 'violin', 'orchestra'] const removedElement = myMusic.splice(3, 2); console.log(myMusic); //[ 'piano', 'guitar', 'drum' ] console.log(removedElement); //removedElement is - [ 'violin', 'orchestra' ]
So we can start at any index and remove as many items as we want.
Delete All Elements Beginning from a Specified Index
We can delete all elements in the array starting from whatever index we want.
Let’s say, for example, we want to remove all starting from index 1. Once it gets to index 1, every element starting from index 1 would be deleted.
const myMusic = ['piano', 'guitar', 'drum', 'violin', 'orchestra'] const removedElement = myMusic.splice(1); console.log(myMusic); //[ 'piano' ] console.log(removedElement); //removedElement is - [ 'guitar', 'drum', 'violin', 'orchestra' ]
This code snippet tries to remove all elements starting from index 1. Where index 1 is ‘guitar’ in the array.
Since counting begins from 0, this would return a new array that contains just one element which is ‘piano’.
This is because during the counting ‘piano’ appears to be on index 0 and counting begins at index 1. Index 0 would be omitted making it return that result.
How to use the splice() method with negative index
So what happens if we add a negative number as the start
parameter? If the start
is negative, it will count backward from the end of the array and remove the elements.
Check the below example.
let favoriteFruits = ["🍓", "🥑", "🍊", "🍇"]; let removedFruits = favoriteFruits.splice(-2); console.log(favoriteFruits); //[ '🍓', '🥑' ] console.log(removedFruits); //[ '🍊', '🍇' ]
In the above example, we have added the start
parameter as -2. This will start counting from the end of the array and remove items.
Conclusion
This array method modifies an array by removing or replacing existing elements in it. It takes the starting index, the count(number of elements you want to remove) and it also optionally takes new elements which are placed at the end of the array.
This method changes the array on which it is called upon and returns an array with the removed or replaced items.
So, if you need to perform a task on an array, and you don’t want the original array changed, the JavaScript array’s splice()
method should be avoided because they change your data.
Resource
- JavaScript Array Splice Issue
- MDN – splice
- JavaScript – Splice, Slice, Split
- JavaScript Array splice
- Splice Method in JavaScript
Add comment