Modifying an Array
Adding, removing, and replacing elements in an array: splice()
The splice()
method is a versatile array method in JavaScript that allows you to modify an array by adding, removing, or replacing elements. It directly changes the original array and returns an array of the removed elements.
The splice()
method takes three main arguments: the start index, the number of elements to remove (optional), and the elements to add (optional).
By specifying a start index, you can define where the changes should occur in the array. The method can then remove a specified number of elements, add new elements, or both, depending on the parameters provided. This makes splice()
a powerful tool for modifying arrays in place.
-
start
: The index at which to start modifying the array. -
deleteCount
: (Optional) Number of elements to remove from the array. -
item1, item2
: (Optional) Elements to add starting from the start index.
Adding Elements
The splice()
method can add new elements to an array. New elements can be inserted at the specified start index by setting the deleteCount
parameter (the second parameter) to 0.
Letβs use the splice()
method to modify an array by adding elements:
Removing Elements
The splice()
method can also remove elements from an array. By specifying the start
index and deleteCount
, a specific number of elements can be removed starting at a given position.
Letβs use the splice()
method to modify an array by removing elements:
Replacing Elements
The splice()
method can replace existing elements by removing some and adding others at the same index.
Letβs use the splice()
method to modify an array by replacing elements:
Swap elements in an array
Another useful application of the splice()
function is to swap elements within an array.
This can be particularly handy when rearranging elements without using additional variables or temporary arrays. Hereβs how you can do it:
- Identify the indices of the two elements you want to swap.
- Use
splice()
to remove the element at one index and store it temporarily. - Use
splice()
again to insert the removed element at the position of the other element and vice versa.
Here is an example of using the splice()
function to swap elements in an array: