Array.toSpliced()
The Array.toSpliced()
method in JavaScript returns a shallow copy of an array with elements added, removed, or replaced without modifying the original array. This method is a non-destructive version of Array.splice()
.
Syntax
toSpliced(start)
toSpliced(start, deleteCount)
toSpliced(start, deleteCount, item1)
toSpliced(start, deleteCount, item1, item2)
toSpliced(start, deleteCount, item1, item2, /* …, */ itemN)
Parameters
Parameter | Description |
---|---|
start | An integer specifying the index at which to begin modifying the array. Negative values count back from the end of the array. |
deleteCount | An integer indicating the number of elements to remove starting from start . Defaults to 0 if omitted. |
item1, item2, ..., itemN | Optional elements to add to the array starting at start . |
Return Value
The toSpliced()
method returns a new array with the specified modifications applied, leaving the original array unchanged.
Examples
1. Removing Elements
This example demonstrates how to remove elements starting from a specific index using toSpliced()
.
const array = [1, 2, 3, 4, 5];
// Remove 2 elements starting from index 1
const result = array.toSpliced(1, 2);
console.log(result);
Output
[1, 4, 5]
toSpliced(1, 2)
removes 2 elements starting from index 1.
2. Adding Elements
Use toSpliced()
to add elements at a specific index without removing any existing elements.
const array = [1, 2, 3, 4, 5];
// Add elements at index 2
const result = array.toSpliced(2, 0, 6, 7);
console.log(result);
Output
[1, 2, 6, 7, 3, 4, 5]
toSpliced(2, 0, 6, 7)
inserts6
and7
at index 2 without removing any elements.
3. Replacing Elements
Elements can be replaced by specifying a deleteCount
and providing new items.
const array = [1, 2, 3, 4, 5];
// Replace 2 elements at index 1
const result = array.toSpliced(1, 2, 6, 7);
console.log(result);
Output
[1, 6, 7, 4, 5]
toSpliced(1, 2, 6, 7)
replaces 2 elements at index 1 with6
and7
.
4. No Deletions or Additions
If no deleteCount
is specified, toSpliced()
simply makes a shallow copy of the original array.
const array = [1, 2, 3, 4, 5];
// Create a shallow copy
const result = array.toSpliced();
console.log(result);
Output
[1, 2, 3, 4, 5]
The array remains unchanged because no modifications were specified.