Deleting Items from Javascript Arrays

A common question people ask me is how to delete items from an array in javascript. Reason being, javascript arrays dont have a function named delete. The function you’re looking for is called splice.

splice takes up to 2 arguments: the index at which you want to delete the item, and amount of items starting from that index that you want to delete.


var array = ["January","February","March","April"];

array.splice(2,1);

the output of the previous block of code would be:

[“January”,”February”,”April”]

with that, I added 2 simple functions to the Array prototype to make deleting objects a lot easier


Array.prototype.removeAt = function(index)
{
 this.splice(index,1);
}

Array.prototype.removeItem = function(item)
{
 var index = this.indexOf(item);
 if(index>=0)
 this.splice(index,1);
}

and use them like this:


array.removeAt(2);

//the array should now be ["January","February"]

array.removeItem("February");

//the array should now be ["January"]

hope this helps!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s