Array.prototype.splice
Removes, replaces or inserts elements in the middle of an array.
Available since: ES3
Syntax
array.splice(start, deleteCount, item1, /* … */)Parameters
| Parameter | Type | Description |
|---|---|---|
| start | number | The position where the change starts. A negative one counts from the end. |
| deleteCount | number | Optional. How many elements to remove. All the rest by default. |
| item1, … | any | Optional. Elements to insert in place of the removed ones. |
Return value
ArrayAn array of the removed elements.
Examples
Removing one element at an index:
const letters = ['a', 'b', 'c', 'd'];
letters.splice(1, 1);
console.log(letters);Output:
[
"a",
"c",
"d"
]Inserting without removing — deleteCount is 0:
const letters = ['a', 'd'];
letters.splice(1, 0, 'b', 'c');
console.log(letters.join(''));Output:
abcdReplacing and getting the removed part:
const letters = ['a', 'b', 'c'];
const removed = letters.splice(1, 2, 'X');
console.log(removed.join(''), letters.join(''));Output:
bc aXNotes
Do not confuse it with slice(): splice() changes the original array, slice() does not. The non-mutating version is toSpliced().
See also
- Array.prototype.slice — Returns part of an array.
- Array.prototype.toSpliced — Returns a copy of an array with elements removed, replaced or inserted.
Related recipes
In the tutorial
- Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.