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

</>
Copy
toSpliced(start)
toSpliced(start, deleteCount)
toSpliced(start, deleteCount, item1)
toSpliced(start, deleteCount, item1, item2)
toSpliced(start, deleteCount, item1, item2, /* …, */ itemN)

Parameters

ParameterDescription
startAn integer specifying the index at which to begin modifying the array. Negative values count back from the end of the array.
deleteCountAn integer indicating the number of elements to remove starting from start. Defaults to 0 if omitted.
item1, item2, ..., itemNOptional 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().

</>
Copy
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]
  1. 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.

</>
Copy
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]
  1. toSpliced(2, 0, 6, 7) inserts 6 and 7 at index 2 without removing any elements.

3. Replacing Elements

Elements can be replaced by specifying a deleteCount and providing new items.

</>
Copy
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]
  1. toSpliced(1, 2, 6, 7) replaces 2 elements at index 1 with 6 and 7.

4. No Deletions or Additions

If no deleteCount is specified, toSpliced() simply makes a shallow copy of the original array.

</>
Copy
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.