How to Remove an Array Element Using the "array.splice()" Method in JavaScript?

To remove an element from a JavaScript array using the Array.prototype.splice() method, you need to do the following:

  1. Pass the index of the array element you wish to remove as the first argument to the method, and;
  2. Pass the number of elements you wish to remove as the second argument to the method.

Please be aware that the Array.prototype.splice() method will change/mutate the contents of the original array by removing the item(s) from it. The returned value, if you're interested, will be an array of items that were removed from the original array. If no elements are removed, an empty array is returned.

For example, to remove only one item at index 1, you would do the following:

const array = [ 'foo', 'bar', 'baz', 'qux' ];
const deletedItem = array.splice(1, 1);

console.log(array); // ['foo', 'baz', 'qux']
console.log(deletedItem); // ['bar']

To remove two items starting from index 1, you would do the following:

const array = [ 'foo', 'bar', 'baz', 'qux' ];
const deletedItems = array.splice(1, 2);

console.log(array); // ['foo', 'qux']
console.log(deletedItems); // ['bar', 'baz']

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.