Array.prototype.splice()

Summary: In this tutorial, you will learn how to use the JavaScript Array splice() method to delete existing elements, insert new elements, and replace elements in an array.

JavaScript Array type provides a very powerful splice() method that allows you to insert, replace, and delete an element from an array.

The splice() method modifies (or muate) the original array. To create a new array from the original with some element inserted, deleted, and replaced, you can use the toSpliced() method.

Deleting elements using the splice() method

To delete elements in an array, you pass two arguments into the splice() method as follows:

const removedElements = array.splice(start, deleteCount);Code language: PHP (php)

The start argument specifies the position of the first item to delete and the deleteCount argument determines the number of elements to delete.

The splice() method changes the original array and returns an array that contains the deleted elements. For example:

let scores = [1, 2, 3, 4, 5];

let deletedScores = scores.splice(0, 3);

console.log({ scores });
console.log({ deletedScores });Code language: JavaScript (javascript)

Output:

{ scores: [ 4, 5 ] }
{ deletedScores: [ 1, 2, 3 ] }Code language: CSS (css)

How it works.

First, define an array scores that includes five numbers from 1 to 5.

let scores = [1, 2, 3, 4, 5];Code language: JavaScript (javascript)

Second, delete three elements of the scores array starting from the first element.

let deletedScores = scores.splice(0, 3);Code language: JavaScript (javascript)

Third, display the scores array and return value to the console:

console.log(deletedScores); // [1, 2, 3]Code language: JavaScript (javascript)

The following picture illustrates how scores.splice(0,3) works: