98 of 264 menu

splice method

The splice method removes or adds elements to an array. You can only remove items, only add items, or do both at the same time. The method is very versatile and difficult to understand. The method changes the array itself and returns an array of removed elements.

The first parameter of the method is the number of the array element to be removed. The second parameter is how many elements of the array should be removed. If it is set to 0, then the elements will not be removed (only new ones will be added). Then, separated by commas, there are elements that need to be added to the array (these parameters are optional). These elements will be added instead of the removed ones.

If there was no deletion (when the second parameter is 0), the elements will be inserted into the array starting from the position specified by the first parameter of the method. The first parameter can be negative. In this case, the position count will start not from the beginning of the array, but from the end. The last element in this case will have the number -1.

Syntax

array.splice(from where to remove, how much to remove, [insert], [insert]...);

Example

Let's remove three elements starting from the first:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.splice(1, 3); console.log(arr);

The code execution result:

['a', 'e']

Example

Let's output the array of removed elements:

let arr = ['a', 'b', 'c', 'd', 'e']; let del = arr.splice(1, 3); console.log(del);

The code execution result:

['b', 'c', 'd']

Example

Let's first remove the element with the number 2, and then insert three more new elements instead:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.splice(2, 1, '1', '2', '3'); console.log(arr);

The code execution result:

['a', 'b', '1', '2', '3', 'd', 'e']

Example

Let's not delete anything now, but at the position 2, insert three more new elements:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.splice(2, 0, '1', '2', '3'); console.log(arr);

The code execution result:

['a', 'b', '1', '2', '3', 'c', 'd', 'e']

Example . Negative value

Let's remove the second to last element:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.splice(-2, 1); console.log(arr);

The code execution result:

['a', 'b', 'c', 'e']

See also

  • the slice method
    that also cuts off parts of an array
  • the shift method
    that removes the first element of an array
  • the pop method
    that removes the last element of an array
byenru