Javascript Reference - JavaScript Array splice() Method








splice() inserts items into the middle of an array. splice() can do three things to an array:Deletion, Insertion and Replacement

This method changes the original array after operation.

Browser Support

splice() Yes Yes Yes Yes Yes

Syntax

array.splice(index,howmany,item1,.....,  itemX)

Parameter Values

Parameter Description
index Required. An integer to set the position to add/remove/replace items, Negative values means "from the end of the array".
howmany Required. The number of elements to be affected. 0 means no items to remove.
item1, ..., itemX Optional. The new item(s) to be added to the array




Return Value

It returns a new Array containing the removed items if there is any.

Deletion

Items can be deleted from the array by specifying just two arguments:

  • the position of the first item to delete and
  • the number of items to delete.

For example, splice(0, 2) deletes the first two items.


var colors = ["A", "B", "C", "D", "E"]; 
var colors2 = colors.splice(0,2); 

console.log(colors); //C,D,E

The code above generates the following result.





Insertion

Items can be inserted into a specific position by providing three or more arguments:

  • the starting position,
  • 0,
  • any number of items to insert.

0 means deleting zero number of items from the array. You can specify a fourth parameter, or any number of other parameters to insert.


var colors = ["A", "B", "C", "D", "E"]; 
var colors2 = colors.splice(2,0,"A","B","C"); 

console.log(colors); //A,B,A,B,C,C,D,E

The code above generates the following result.

Replacement

Items can be inserted and deleted with three arguments:

  • the starting position,
  • the number of items to delete,
  • any number of items to insert.

The number of items to insert doesn't have to match the number of items to delete.

splice(2, 1, "A", "B") deletes one item at position 2 and then inserts the strings "A" and "B" at position 2. splice() returns an array with removed items or empty array if no items were removed.


var colors = ["A", "B", "C"]; 
//insert two values, remove one 
var removed = colors.splice(1, 1, "D", "E"); 
console.log(colors); //A,D,E,C
console.log(removed); //B

The code above generates the following result.