JavaScript Array toSpliced() Method
In JavaScript, Array.toSpliced()
method is used to create a new array with some elements removed and/or replaced at a given index, without modifying the original array.
The difference between the new toSpliced() method and the old splice() method is that the new method creates a new array, keeping the original array unchanged, while the old method alters the original array.
Syntax:
array.toSpliced(start, deleteCount, item1, item2, ..., itemN)
Parameters:
start
: zero-based index from which the array will start changing.deleteCount
: integer indicating the number of elements to remove fromstart
.item1, item2, ..., itemN
: The elements to add to the array, beginning fromstart
Return value:
The return value is a new array that consists of all elements before start
, item1
, item2
, …, itemN
, and all elements after start
+ deleteCount
.
Example 1: In the below example, the Array.toSpliced() method is used to copy a part of a given array without modifying it.
const numbers = [10, 20, 30, 40, 50];
const sliced = numbers.toSpliced(1, 3);
console.log("Old Array: ", numbers);
console.log("New Array: ", sliced);
Output:
Old Array: [10, 20, 30, 40, 50]
New Array: [10, 50]
Example 2: In the below code, the Array.toSpliced() method is used to insert a value at specified index in array.
const days = ["Mon", "Wed", "Thurs", "Fri"];
const day2 = days.toSpliced(1, 0, "Tue");
console.log("New Array", day2);
console.log("Old Array", days);
Output:
New Array: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri']
Old Array: ['Mon', 'Wed', 'Thurs', 'Fri']
Example 3: In below code, the Array.toSpliced() method is used to delete the two words starting from index 2.
const words =
["Apple", "Banana", "Cherry",
"Date", "Elderberry", "Fig"];
const result = words.toSpliced(2, 2);
console.log("New Array: ", result);
console.log("Old Array: ", words);
Output:
New Array: ['Apple', 'Banana', 'Elderberry', 'Fig']
Old Array: ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig']
Example 4: In the below code, the Array.toSpliced() method is used to replace the one at index 2 with two other items.
const items =
["Chair", "Table", "Desk", "Sofa"];
const items2 = items.
toSpliced(1, 1, "Bookshelf", "Lamp");
console.log("New Array: ", items2);
console.log("Old Array: ", items);
Output:
New Array: ['Chair', 'Bookshelf', 'Lamp', 'Desk', 'Sofa']
Old Array: ['Chair', 'Table', 'Desk', 'Sofa']
Supported Browsers
- Google Chrome
- Edge
- Internet Explorer
- Firefox
- Opera
- Safari