Remove an item from a Javascript array
Posted March 19th, 2010 in Javascript
I recently needed to remove an item from a Javascript array based on the index and while it's easy enough to do this using slice etc there's no inbuilt function to do so.
John Resig's solution
John Resig, who works for Mozilla and is the author of jQuery posted an array remove function on his blog. If you need a Javascript array remove function I would suggest grabbing a copy of the code from his website.
The only change I would suggest making is to surround the code with a condition to see if the function has already been added, e.g.:
if(!Array.prototype.remove) {
// John Resig's array remove function here
};
By doing this, if the function ever be introduced to Javascript natively the native function will be used instead of the one defined in your code.
Related posts:
- Iterate through an associative array the jQuery way (Friday, January 29th 2010)
- Loop through key value pairs from an associative array with Javascript (Friday, April 3rd 2009)
- Assigning values to associative arrays in Javascript (Sunday, December 30th 2007)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
