Remove an item from a Javascript arrayRemove 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:

Comments

blog comments powered by Disqus