splice

Removes or replaces and/or adds new elements of an array.

It takes the following parameters:

  • the index of the element where to start modifying the array
  • the number of elements to delete
  • the elements to insert in the array (optional)

splice returns the elements that have been removed.

const arr = ['1', '2', '5', '6'];

// Insert an element at index 2
arr.splice(2, 0, '3');
console.log(arr);
// => ['1', '2', '3', '5', '6']

// Remove 2 elements, starting at index 3 and insert 2 elements
const removed = arr.splice(3, 2, '4', '5');
console.log(removed);
// => ['5', '6']
console.log(arr);
// => ['1', '2', '3', '4', '5']

// Remove 1 element at index 1
arr.splice(1, 1);
console.log(arr);
// => ['1', '3', '4', '5']

References


Backlinks