Array.splice()
The Array.splice()
method in JavaScript is used to add, remove, or replace elements in an array. It modifies the original array and returns an array containing the deleted elements (if any).
Syntax
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)
Parameters
Parameter | Description |
---|---|
start | An integer specifying the index at which to start changing the array. If negative, it counts from the end of the array. |
deleteCount | (Optional) The number of elements to remove starting from start . If omitted, all elements from start to the end are removed. If set to 0, no elements are removed. |
item1, item2, ..., itemN | (Optional) The elements to add to the array starting from start . |
Return Value
The splice()
method returns an array containing the deleted elements. If no elements are removed, an empty array is returned.
Examples
1. Removing Elements
This example demonstrates how to remove elements from an array using splice()
.
const fruits = ["apple", "banana", "cherry", "date"];
const removed = fruits.splice(1, 2);
console.log(fruits); // ["apple", "date"]
console.log(removed); // ["banana", "cherry"]
Output
[ 'apple', 'date' ]
[ 'banana', 'cherry' ]
Here, splice(1, 2)
removes 2 elements starting from index 1 and returns them.
2. Adding Elements
Elements can be added to the array using splice()
.
const fruits = ["apple", "date"];
fruits.splice(1, 0, "banana", "cherry");
console.log(fruits);
Output
[ 'apple', 'banana', 'cherry', 'date' ]
In this case, splice(1, 0, "banana", "cherry")
adds the elements at index 1 without removing any elements.
3. Replacing Elements
The splice()
method can replace elements by removing and adding elements at the same time.
const fruits = ["apple", "banana", "cherry"];
fruits.splice(1, 1, "blueberry");
console.log(fruits); // ["apple", "blueberry", "cherry"]
Output
[ 'apple', 'blueberry', 'cherry' ]
Here, splice(1, 1, "blueberry")
removes one element at index 1 and inserts “blueberry” at the same position.
4. Using Negative Start Index
If the start
parameter is negative, the method counts from the end of the array.
const fruits = ["apple", "banana", "cherry", "date"];
const removed = fruits.splice(-2, 1);
console.log(fruits); // ["apple", "banana", "date"]
console.log(removed); // ["cherry"]
Output
[ 'apple', 'banana', 'date' ]
[ 'cherry' ]
Here, splice(-2, 1)
removes one element starting from the second-to-last position.
5. Removing All Elements from a Start Index
When deleteCount
is omitted, all elements from start
to the end of the array are removed.
const fruits = ["apple", "banana", "cherry", "date"];
const removed = fruits.splice(2);
console.log(fruits); // ["apple", "banana"]
console.log(removed); // ["cherry", "date"]
Output
[ 'apple', 'banana' ]
[ 'cherry', 'date' ]
Here, splice(2)
removes all elements from index 2 onward.