avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Insert, Replace or Delete Element in a JavaScript Array with Array.prototype.splice() method

Mon Oct 29 2018

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Insert An Item in An Array

const arr = [1, 2, 3, 4, 5];
arr.splice(2, 0, 6); // Add 6 at index 2 delete 0 items, which means insert.
console.log(arr); // [1, 2, 6, 3, 4, 5]

Delete An Item in An Array

const arr = [1, 2, 3, 4, 5];
arr.splice(2, 1); // Delete 1 item at index 2, which means delete.
console.log(arr); // [1, 2, 4, 5]

Replace An Item in An Array

const arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, 6); // Add 6 at index 2 delete 1 item, which means replace.
console.log(arr); // [1, 2, 6, 4, 5]

Syntax

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)