JS: Array.prototype.toSpliced ⭕

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2023)

similar to Array.prototype.splice but return a copy.

Example. clear all elements

// clear all elements
const xx = [3, 4, 5];
const yy = xx.toSpliced(0);

// original not changed
console.assert(xx.length === 3);

console.assert(yy.length === 0);

Example. remove rest starting at index 2

// remove rest starting at index 2
const xx = [0, 1, 2, 3, 4, 5];
const yy = xx.toSpliced(2);
console.log(yy);
// [ 0, 1 ]

Example. delete n items

const xx = [0, 1, 2, 3, 4, 5];
// remove 3 elements, starting at index 2
const yy = xx.toSpliced(2, 3);
console.log(yy);
// [ 0, 1, 5 ]

Example. add new items

// example of adding element to array

const xx = [0, 1, 2, 3, 4, 5];

// add "b" before index 2
const yy = xx.toSpliced(2, 0, "b");

console.log(yy);
// [ 0, 1, "b", 2, 3, 4, 5 ]
const xx = [0, 1, 2, 3];

// insert a array as item
const yy = xx.toSpliced(2, 0, [88, 99]);

console.log(yy);
// [ 0, 1, [ 88, 99 ], 2, 3 ]
const xx = [0, 1, 2, 3];

// a function that returns array
const ff = () => [8, 9];

// insert the items of an array
const yy = xx.toSpliced(2, 0, ...ff());

console.log(yy);
// [ 0, 1, 8, 9, 2, 3 ]

Example. replace a slice (delete and add)

const xx = [0, 1, 2, 3, 4, 5];

// example of array toSpliced.
// start at index 2, removed 3 items, add "a"

const yy = xx.toSpliced(2, 3, "a");

console.log(yy);
// [ 0, 1, "a", 5 ]