The splice() method in Javascript is used to remove, replace and/or add elements in an array. The splice() method changes the original array.

Syntax

Array.splice(start, delete, item1, item2)

The first argument start contains the index value from where we want to add or delete elements.

The second argument delete contains the count of the number of elements we want to delete.

If we specify additional arguments after the delete argument, they are inserted in the array according to the start index.

The method returns the deleted elements.

Delete elements using splice()

let numbers = [7, 8, 3, 4, 5];

let deletedNums = numbers.splice(1, 2);

console.log(deletedNums); // [8, 3]

console.log(numbers); // [7, 4, 5]

In the above example, we have specified the start index as 1. This means that the splice will start from the second element 8. Next, we have specified the delete count as 2. So, the splice method will delete elements 8 and 3. The method returns the deleted elements which are stored in deletedNums.

Similarly,

let numbers = [7, 8, 3, 4, 5];

let deletedNums = numbers.splice(2, 3);

console.log(deletedNums); // [3, 4, 5]

console.log(numbers); // [7, 8]

The splice() method mutates the original array numbers.

If we do not specify the delete count the splice() method will all the elements from the start index.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let deletedNums = numbers.splice(3);

console.log(deletedNums); // [4, 5, 6, 7, 8, 9, 10]

console.log(numbers); // [1, 2, 3]

Insert elements using splice()

To insert elements in the splice() method we need to pass the elements to be inserted after the second argument. The elements get inserted according to the start index specified.

let numbers = [1, 2, 3, 4, 5];

let deletedNums = numbers.splice(2, 0, 6, 7);

console.log(deletedNums); // []

console.log(numbers); // [1, 2, 6, 7, 3, 4, 5]

In this example, we want to insert two elements 6 and 7 starting at the index 2. Hence, the first argument is 2. The second argument, which is the delete count is 0 since we do not want any items to be deleted. The remaining arguments are the items we want to insert into the array. In this case, it is 6 and 7.

deletedNums returns an empty array since there are no items that have been deleted in the process.

We can specify the delete count if we need to delete and insert at the same time.

let numbers = [1, 2, 3, 4, 5];

let deletedNums = numbers.splice(2, 2, 6, 7);

console.log(deletedNums); // [3, 4]

console.log(numbers); // [1, 2, 6, 7, 5]