The syntax for using the splice() method is as follows:
array.splice(start, deleteCount, item1, item2, ...)
- start: The index at which to start changing the array. If start is negative, it specifies an offset from the end of the array. For example, -2 means the second-to-last element in the array.
- deleteCount: It indicate the number of elements in the array to remove from start.
- item1, item2, etc.: The elements to add to the array, beginning at the start index.
Examples Of Splice Array Method
Here are some examples of using the splice() method:
Removing Elements from an Array
In the example below, we set the first paramater of the splice method. This means start removing elements at index 2, and the we set second parameter 1, this represent the number of elements that will be removed.
let fruits = ['apple', 'banana', 'orange', 'mango']; let removedFruit = fruits.splice(2, 1); // Removes the element at index 2 (orange) console.log(fruits); // Output: ['apple', 'banana', 'mango'] console.log(removedFruit); // Output: ['orange']
Adding Elements to an Array:
If you add element instead of removing, so you can set the second parameter 0. The first paramare has same mission in this example, To sum up it adds two elements, which are 6 and 7 starting at index 2.
let numbers = [1, 2, 3, 4, 5]; numbers.splice(2, 0, 6, 7); // Adds 6 and 7 at index 2 console.log(numbers); // Output: [1, 2, 6, 7, 3, 4, 5]
Replacing Elements in an Array:
The following example shows that if your second parameter is not zero and you attach some elements to the function. The split method performs replacing action. The function below starts replacing two elements at index 1.
let colors = ['red', 'green', 'blue', 'yellow']; colors.splice(1, 2, 'orange', 'purple'); // Replaces 'green' and 'blue' with 'orange' and 'purple' console.log(colors); // Output: ['red', 'orange', 'purple', 'yellow']
Thank you for reading.