JS: Array.prototype.splice (remove and add at index)

By Xah Lee. Date: . Last updated: .

splice is the general way to remove or insert consecutive elements, at a given position.

general form is:

xArray.splice(start_index, delete_n_items, new1, new2, etc)

Delete tail

xArray.splice(start)
  • Delete all tail elements starting at index start, including it.
  • start can be negative, meaning, count from right.
  • Return a array of removed elements, or empty array if none removed.
  • Original is modified.

🟢 TIP: To return a copy instead, use Array.prototype.toSpliced.

// clear all elements
const xx = [3, 4, 5];
xx.splice(0);
console.assert(xx.length === 0);
// remove rest starting at index 2
const xx = [0, 1, 2, 3, 4, 5];
const xout = xx.splice(2);

// removed items
console.log(xout);
// [ 2, 3, 4, 5 ]

// original is modified
console.log(xx);
// [ 0, 1 ]
// remove last 2 items
const xx = [0, 1, 2, 3, 4, 5];
xx.splice(-2);
console.log(xx);
// [ 0, 1, 2, 3 ]

Delete n items

xArray.splice(start, n)

Delete n items.

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

// remove 3 elements, starting at index 2
const xout = xx.splice(2, 3);

// the new value
console.log(xx);
// [ 0, 1, 5 ]

// removed items
console.log(xout);
// [ 2, 3, 4 ]

Delete items and add items at a position

xArray.splice(start, n, new1, new2, etc)

Add new items.

// example of adding element to array

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

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

console.log(xx);
// [ 0, 1, "b", 2, 3 ]

// removed items
console.log(xout);
// []
const xx = [0, 1, 2, 3];
// insert a array as item
xx.splice(2, 0, [8, 9]);
console.log(xx);
// [ 0, 1, [ 8, 9 ], 2, 3 ]

🟢 TIP: use Spread Operator to avoid nested array.

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

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

// insert a array as items
xx.splice(2, 0, ...ff());

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

Example. Replace a Slice (Delete and Add)

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

/*
example of array splice, remove some, add some
start at index 2, removed 3 items, add "a"
*/
const yy = xx.splice(2, 3, "a");

// the new value
console.assert(JSON.stringify(xx) === `[0,1,"a",5]`);

// removed items
console.assert(JSON.stringify(yy) === "[2,3,4]");

JavaScript. Add or Remove Subarray