The splice()
method in JavaScript is used to modify an array by adding or removing elements from it. it Returns an array containing the deleted elements.
arr.splice(start, deleteCount, item1, ..., itemN)
start
: An integer that specifies the index at which to start changing the array.deleteCount
: An integer that specifies the number of elements to remove from the array starting at thestart
index. If this argument is 0, no elements are removed.item1
,item2
, …,itemN
: Elements to be added to the array, starting at thestart
index. If no elements are provided,splice()
will only remove elements from the array.
JavaScript Array splice example
Simple example code that demonstrates how to use the splice() method:
<!DOCTYPE html>
<html>
<body>
<script>
const myArray = ['apple', 'banana', 'cherry', 'date'];
// Remove one element starting at index 2
myArray.splice(2, 1);
console.log(myArray)
// Remove two elements starting at index 1 and add two elements in their place
myArray.splice(1, 2, 'orange', 'grape');
console.log(myArray)
// Add two elements starting at index 2
myArray.splice(2, 0, 'lemon', 'lime');
console.log(myArray)
</script>
</body>
</html>
Output:
Using splice() for different deleteCount values and different start values
const arr = ['apple', 'banana', 'cherry', 'date'];
// Removing one element starting from index 2
arr.splice(2, 1); // Returns ['cherry']
// ['apple', 'banana', 'date']
// Removing two elements starting from index 1
arr.splice(1, 2); // Returns ['banana', 'date']
// ['apple']
// Removing all elements from index 1
arr.splice(1); // Returns ['']
// ['apple']
// Adding two elements starting from index 2
arr.splice(2, 0, 'lemon', 'lime'); // Returns []
//['apple', 'lemon', 'lime']
// Replacing two elements starting from index 1
arr.splice(1, 2, 'orange', 'grape'); // Returns ['lemon', 'lime']
//['apple', 'orange', 'grape']
Comment if you have any doubts or suggestions on this Js array method.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version