Array.prototype.toSpliced
Returns a copy of an array with elements removed, replaced or inserted.
Available since: ES2023
Syntax
array.toSpliced(start, deleteCount, item1, /* … */)Parameters
| Parameter | Type | Description |
|---|---|---|
| start | number | The position where the change starts. |
| deleteCount | number | Optional. How many elements to remove. |
| item1, … | any | Optional. Elements to insert in place of the removed ones. |
Return value
ArrayA new array with the changes.
Examples
Removing an element without changing the original:
const letters = ['a', 'b', 'c'];
console.log(letters.toSpliced(1, 1).join(''));
console.log(letters.join(''));Output:
ac
abcInserting in the middle:
console.log([1, 4].toSpliced(1, 0, 2, 3).join(', '));Output:
1, 2, 3, 4Notes
Unlike splice(), it returns the whole new array rather than the removed elements.
See also
- Array.prototype.splice — Removes, replaces or inserts elements in the middle of an array.
- Array.prototype.with — Returns a copy of an array with one element replaced.
- Array.prototype.slice — Returns part of an array.
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.