JS: Array.prototype.toSpliced

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2023)

similar to JS: 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.log(xx.length === 3);

console.log(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(JSON.stringify(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(JSON.stringify(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(JSON.stringify(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(JSON.stringify(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(JSON.stringify(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(JSON.stringify(yy) === `[0,1,"a",5]`);

JavaScript. Add or Remove Subarray