How to Use the splice() Method
The basic idea of the splice()method is as follows:
splice(start, deleteCount, item1, item2, itemN)
Parameter 1: start
is the index at which to start changing the array.
Parameter 2: deleteCount
is an integer indicating the number of elements in the array to remove from start
.
Parameter 3: Items are the elements to add to the array, beginning from start
.
!! IMPORTANT !!
The splice() method modifies the original array and returns an array of the deleted items.
Case 1: Only Setting start
const numbers = [0, 1, 2, 3, 4];
const removedNumbers = numbers.splice(2);
console.log(numbers); // [0, 1]
console.log(removedNumbers); // [2, 3, 4]
const numbers = [0, 1, 2, 3, 4];
const removedNumbers = numbers.splice(-3);
console.log(numbers); // [0, 1]
console.log(removedNumbers); // [2, 3, 4]
Case 2: Setting start
and deleteCount
const numbers = [0, 1, 2, 3, 4];
const removedNumbers = numbers.splice(2, 2);
console.log(numbers); // [0, 1, 4]
console.log(removedNumbers); // [2, 3]
const numbers = [0, 1, 2, 3, 4];
const removedNumbers = numbers.splice(-3, 2);
console.log(numbers); // [0, 1, 4]
console.log(removedNumbers); // [2, 3]
Case 3: Setting start
, deleteCount
, and items
const numbers = [0, 1, 2, 3, 4];
const removedNumbers = numbers.splice(2, 2, 'item1', 'item2');
console.log(numbers); // [0, 1, "item1", "item2", 4]
console.log(removedNumbers); // [2, 3]
const numbers = [0, 1, 2, 3, 4];
const removedNumbers = numbers.splice(-3, 2, 'item1', 'item2');
console.log(numbers); // [0, 1, "item1", "item2", 4]
console.log(removedNumbers); // [2, 3]