Array. prototype. splice()
Removes, replaces, or inserts elements in place, changing the array.
- Returns
- An array of the removed elements (it can be empty).
- Changes the original
- Yes
Example
#const list = ['HTML', 'CSS', 'PHP', 'JavaScript']
const removed = list.splice(2, 1)
console.log(removed)
console.log(list)
list.splice(1, 0, 'Sass')
console.log(list)Definition and usage
#The splice(start, deleteCount, ...items) method changes the original array. Starting at index start, it removes deleteCount elements and inserts the given new elements in their place. It returns an array of the removed elements.
With a single call you can remove an element (splice(i, 1)), insert a new one without removing anything (splice(i, 0, x)), or swap a chunk for other values.
If you don’t want to mutate the data, use the newer toSpliced() method, which works the same way but returns a new array.
Syntax
#array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, …)Parameters
#start
number
The index the changes start at. A negative value counts from the end.deleteCount
optional
The number of elements to remove. Omitted means removing everything to the end.item1…itemN
optional
The elements to insert atstart.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- To remove an element by condition,
filter()is usually the better choice, since it doesn’t mutate the array. - Don’t remove elements with
splice()in a loop going forward, since the indexes shift. Go backward instead, or usefilter().
Related entries
#- slice() vs splice()slice() copies a section of the array without changing the original, while splice() removes, inserts, or replaces elements in place, mutating the array.
- Array.prototype.slice()Returns a copy of part of an array without changing the original.
- Array.prototype.findIndex()Returns the index of the first element that matches a condition, or -1.
- Array.prototype.filter()Creates a new array with the elements for which the function returned true.
- Array.prototype.push()Adds elements to the end of an array and returns its new length.
- Array.prototype.toSpliced()Removes, inserts, or replaces elements in a copy of the array. The original is left unchanged.
Spotted a mistake or missing an example? Write to us.