JavaScript Array toSpliced()Method
Example
Reverse the order of the elements in the array:
//Create an array
const sites = ["Google", "Example", "JYSHARE", "Taobao"];
//Add 'Zhihu' and 'Wiki' at position 2
const sites2 = sites.toSpliced(2, 0, "Zhihu", "Wiki");
document.getElementById("demo").innerHTML = sites2;
Output:
Google,Example,Zhihu,Wiki,JYSHARE,Taobao
Try it Yourself »
Definition and Usage
The toSpliced() method is used to add and/or remove elements from an array.
The toSpliced() method returns a new array.
The toSpliced() method does not modify the original array.
toSpliced() is the copying version of the splice() method.
Browser Support
toSpliced() is an ES2023 feature.
As of July 2023, all modern browsers support this feature:
| Chrome 110 | Edge 110 | Firefox 115 | Safari 16.4 | Opera 96 |
| Feb 2023 | Feb 2023 | Jul 2023 | Mar 2023 | May 2023 |
Syntax
array.toSpliced(index, count, item1, ..., itemX)
Parameters
| Parameter | Description |
|---|---|
| index (required) | The index (position) of the element to add or remove. Negative values count from the end of the array. |
| count (optional) | The number of elements to remove. |
| item1, ... (optional) | The new elements to add. |
Return Value
| Type | Description |
|---|---|
| Array | A new array containing the modified elements. |
More Examples
Remove elements:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruits2 = fruits.toSpliced(2, 2); // ["Banana", "Orange"]
const fruits2 = fruits.toSpliced(2, 2); // ["Banana", "Orange"]
Remove and add elements:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruits2 = fruits.toSpliced(2, 1, "Lemon", "Kiwi"); // ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
const fruits2 = fruits.toSpliced(2, 1, "Lemon", "Kiwi"); // ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
Other Extensions
JavaScript Array Object