Splice() in JavaScript – How to Use the.splice

The splice() method can be applied on a JavaScript array.

It can be used to delete existing elements, insert new elements, and replace elements in an array.

The General Syntax:

arr.splice( start [, deleteCount[, item1[, item2[, . . .] ] ] ])

/**

* start:

index at which to start changing the array

* delete Count (optional ) :

number of elements to remove (from start position)

* item1, item2,  . . . (optional) :

elements to add to the array (from start position )

* /

Deletion:

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

Array.splice( position, num);

// delete the first 3 elements

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

scores.splice(0, 3);

// output: [4, 5]

Insertion:

The position specifies the starting position in the array that the new elements will be inserted at. The subsequent arguments are the elements that will be inserted starting from the specified position.

Array.splice( position, new_element_1, new_element_2, . . .);

// inserts “purple” in the second index position

let colors = [‘ red’, ‘green’, ‘blue’];

colors.splice(2, ‘purple’);

// output: [“red” “green”, “purple”, “blue”]

Replacement:

The following statement replaces the second element by a new one.

Array.splice( start ,deleteCount, element_1, element_2,.. . );

/ / delete at index 1 and insert “Python” in that position

let languages = [‘C’, ‘C++’, ‘Java’, ‘JavaScript ‘ ];

languages.splice(1, 1, ‘Python ‘ );

// output: [“C”, “Python”, “Java”, “JavaScript”]

/ /  “C++” is replaced by “Python”

Leave a Reply

Your email address will not be published. Required fields are marked *