How to add, remove, and replace items using Array.splice() in JavaScript

published: 19 Sep 2022

2 min read

How to add, remove, and replace items using Array.splice() in JavaScript

In JavaScript, the Array.splice() method can be used to add, remove, and replace elements from an array. This method modifies the contents of the original array by removing or replacing existing elements and/or adding new elements in place. Array.splice() returns the removed elements (if any) as an array.

Syntax

Here is the syntax of Array.splice():

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
  • start - The starting index for changing elements in the array.
  • deleteCount - An integer indicating the number of elements in the array to remove from start. If deleteCount is 0 or negative, no elements are removed. In this case, you have to specify at least one new element.
  • item1, item2, ... - The elements to be added to the array, beginning from start. If no elements are specified, splice() will only remove elements from the array.

Removing Elements

Here is example that uses Array.splice() to remove first two elements from the beginning of an array:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

// remove first elements
const removed = fruits.splice(0, 2);

console.log(fruits); // ['Mango', 'Banana']
console.log(removed); // ['Apple', 'Orange']

If the deleteCount is omitted, all the elements starting from start are removed from the array:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const removed = fruits.splice(1);

console.log(fruits); // ['Apple']
console.log(removed); // ['Orange', 'Mango', 'Banana']

Replacing Elements

You can also replace the removed items with the new one by using Array.splice():

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const removed = fruits.splice(1, 2, 'Cherry', 'Watermelon');

console.log(fruits); // ['Apple', 'Cherry', 'Watermelon', 'Banana']
console.log(removed); // ['Orange', 'Mango']

Adding Elements

To add new elements with Array.splice(), just set the deleteCount to zero and pass new items:

const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const removed = fruits.splice(2, 0, 'Cherry');

console.log(fruits); // ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']
console.log(removed); // []

Browser Compatibility

The Array.splice() method works in all modern browsers, and IE6 and above.

To learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable, take a look at this guide.

How to add, remove, and replace items using Array.splice() in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array