This method modifies the original array and returns the removed elements as a new array.
In this tutorial, you will learn how you can remove, add, or replace elements of an array using the
splice() method. Let's start with removing elements from an array first.
How to remove array elements with splice()
For example, suppose you have an array named
months but you have some day names in the array as follows:
You can use the
splice() method to remove the day names from the
months method and add it to a new array at the same time:
splice() method needs at least one parameter, which is the
start index where the splice operation starts. In the code above, the number
2 is passed to the method, which means
splice() will start removing elements from index
You can also define how many elements you want to remove from the array by passing a second
number argument known as
removeCount. For example, to remove only one element, you can pass the number
1 like this:
When you omit the
splice() will remove all elements from the
start index to the end of the array.
How to remove and add array elements with splice()
The method also allows you to add new elements right after the delete operation. You just need to pass the elements you want to add to the array after the delete count.
The full syntax of the
splice() method is as follows:
The following example shows how you can remove "Monday" and "Tuesday" while adding "March" and "April" to the
How to add new array elements without removing any elements
Finally, you can add new elements without removing any by passing the number
0 to the
removeCount parameter. When no elements are removed, the splice method will return an empty array. You can choose whether to store the returned empty array to a variable or not.
The following example shows how you can add a new element
"March" next to
"February" without deleting any elements. Since the
splice() method returns an empty array, you don't need to store the returned array:
You've just learned how the
splice() method works. Great job!
splice() method is mostly used when you need to delete or add new elements to an array. In some situations, you can also use it to separate an array which has mixed content as in the case above.
When you remove
0 elements from the array, then the method will simply return an empty array. You're always free to either assign the returned array to a variable or ignore it.
Thanks for reading this tutorial
Be sure to check it out 😉