How to use the JavaScript splice() Function

The splice() function in JavaScript is used to remove or replace elements in an array at a specified range of keys.

 

The splice() Syntax

Before we jump into some examples, let's look at the splice() syntax to understand how it works.

 

removed_elements = array.splice(index, count, item1, item2)

 

  • removed_elements – the array of removed element(s).
  • array – the array to work with.
  • index – the start index.
  • count – the number of items to replace/remove from the start index.
  • item1,item2 – the items to replace the old elements with or add to array starting at the start index.

 

Remove Element at Index with splice()

In the example below, we will remove an element at index 1 from the array using the splice() function.

 

var fruit = ['apple', 'orange', 'pear', 'strawberry']

var removed_fruit = fruit.splice(1,1);

console.log(fruit);

console.log(removed_fruit);
["apple", "pear", "strawberry"]
["orange"]

 

The key structure of the original array ends up like this:

 

0: "orange"
1: "pear"
2: "strawberry"

 

Replace Element at Index with splice()

In the example below, we will replace the value of the element at index 2.

 

var fruit = ['apple', 'orange', 'pear', 'strawberry']

var removed_fruit = fruit.splice(2, 1, 'mango');

console.log(fruit);

console.log(removed_fruit);
["apple", "orange", "mango", "strawberry"]
["pear"]

 

Remove Multiple Elements at Index with splice()

Here is another example demonstrating the removal of multiple elements from a start index in an array:

 

var fruit = ['apple', 'orange', 'pear', 'strawberry']

var removed_fruit = fruit.splice(1, 2);

console.log(fruit);

console.log(removed_fruit);
["apple", "strawberry"]
["orange", "pear"]

 

Replace All Elements After Element

To replace all elements after an index, supply array.length as the second argument of splice() like this:

 

var fruit = ['apple', 'orange', 'pear', 'strawberry']

var removed_fruit = fruit.splice(2, fruit.length);

console.log(fruit);

console.log(removed_fruit);
["apple", "orange"]
["pear", "strawberry"]

 

Add Elements at Index X Without Replacing Any

Here we are adding elements after a specified index without removing any:

 

var fruit = ['apple', 'orange', 'pear', 'strawberry']

var removed_fruit = fruit.splice(2, 0, 'mango', 'coconut');

console.log(fruit);

console.log(removed_fruit);
["apple", "orange", "mango", "coconut", "pear", "strawberry"]

[]