Javascript provides us with built in Array objects that have methods and properties. Arrays in Javascript are dynamic and very easy to work with. You can insert, pop, shift, unshift, and iterate over array elements using the provided array methods.
In this post, I want to discuss a very good method called splice()
, that is able to do two things (inserting and removing) elements into and from an array.
Array.prototype.slice()
This method has a special syntax, where the parameters passed to it vary based on the operation it is intended to do. If you have an array called items:
var items = ['pen', 'paper', 'pencil', 'book'];
items.splice(startingIndex, numberOfElementsToDelete, item1, item2, item3....);
startingIndex
is the index at which the element is inserted at OR the index at which the element you want to remove is placed.
numberOfElementsToDelete
is the number of elements you intend to delete, starting at the startingIndex. If you are doing an insert, 0 should be passed as this parameter.
item1, item2, item3 ....
these are the items you intend to insert into the array starting at the 'startingIndex'.
Example of Insert operation:
var items = ['pen', 'paper', 'pencil', 'book'];
items.splice(2, 0, 'Marker', 'Backpack');
The above invocation of splice should modify the items array into the following:
["pen", "paper", "Marker", "Backpack", "pencil", "book"]
We passed 0 as the second parameter since we are not deleting and passed multiple elements to be inserted.
Example of a delete operation:
var items = ['pen', 'paper', 'pencil', 'book'];
items.splice(2, 2);
The second parameter in the invocation of the splice method above has the value 2. That means, we want to remove 2 elements
starting from the index 2 (the first parameter).
The above invocation of splice should modify the items array into the following:
["pen", "paper",]
Remember, there are third and fourth parameters in the above, as our objective was deleting and not inserting elements.