Understanding the splice method
array.splice(start, deleteCount, item1, item2, …)
Let’s break down each parameter:
– start: This parameter specifies the index at which the modification should begin. If the value is negative, it is treated as an offset from the end of the array.
– deleteCount: This parameter determines the number of elements to remove from the array. If set to 0, no elements are removed.
– item1, item2, …: These optional parameters represent the elements to be added to the array at the specified index.
Examples of using splice
To better understand how the splice method works, let’s explore a few examples:
const numbers = [1, 2, 3, 4, 5];
console.log(numbers); // Output: [1, 2, 4, 5]
In this example, we start at index 2 and remove 1 element. As a result, the number 3 is removed from the array.
const fruits = [‘apple’, ‘banana’, ‘cherry’];
fruits.splice(1, 0, ‘orange’, ‘grape’);
console.log(fruits); // Output: [‘apple’, ‘orange’, ‘grape’, ‘banana’, ‘cherry’]
In this example, we start at index 1, remove 0 elements, and add ‘orange’ and ‘grape’ to the array. As a result, the two new elements are inserted at the specified index.
const animals = [‘cat’, ‘dog’, ‘elephant’];
animals.splice(0, 2, ‘lion’, ‘tiger’);
console.log(animals); // Output: [‘lion’, ‘tiger’, ‘elephant’]
In this example, we start at index 0, remove 2 elements, and add ‘lion’ and ‘tiger’ to the array. As a result, the first two elements (‘cat’ and ‘dog’) are replaced with the new elements.
The splice method can also be used to extract elements from an array. By setting the deleteCount parameter to a positive value and omitting the item1, item2, … parameters, we can effectively extract elements from the array without modifying it.
const colors = [‘red’, ‘green’, ‘blue’, ‘yellow’];
const extractedColors = colors.splice(1, 2);
console.log(colors); // Output: [‘red’, ‘yellow’]
console.log(extractedColors); // Output: [‘green’, ‘blue’]
In this example, we start at index 1, remove 2 elements, and store the extracted elements in the extractedColors variable. The original array, colors, is modified to contain only the remaining elements.