JavaScript Array Remove Method

Tagged:  

John Resig just published a handy little JavaScript method to remove elements from an array.

Here's his method:

   1. // Array Remove - By John Resig (MIT Licensed)
   2. Array.prototype.remove = function(from, to) {
   3.   var rest = this.slice((to || from) + 1 || this.length);
   4.   this.length = from < 0 ? this.length + from : from;
   5.   return this.push.apply(this, rest);
   6. };

And here are some examples of its use:


   1. // Remove the second item from the array
   2. array.remove(1);
   3. // Remove the second-to-last item from the array
   4. array.remove(-2);
   5. // Remove the second and third items from the array
   6. array.remove(1,2);
   7. // Remove the last and second-to-last items from the array
   8. array.remove(-2,-1);

Here are the goals he had for the method:

  • It had to add an extra method to an array object that would allow me to remove an item by index (e.g. array.remove(1) to remove the second item).
  • It had to be able to remove items by negative index (e.g. array.remove(-1) to remove the last item in the array).
  • It had to be able to remove a group of items by index, and negative index (e.g. array.remove(0,2) to remove the first three items and array.remove(-2,-1) to remove the last two items).
  • It had to be destructive (modifying the original array).
  • It had to behave like other destructive array methods (returning the new array length - like how push and unshift work).

To get more information about this method, click here to visit John's blog.

The code is really neat, but existing array.splice already covers most of defined goals

True. There's actually a follow-up method that does use splice.

Array.prototype.remove = function(from, to){
this.splice(from, !to || 1 + to - from + (!(to < 0 ^ from >= 0) && (to < 0 || -1) * this.length));
return this.length;
};

Hi all

Seems a shame this is getting so much attention and yet doesn't work in IE7.

Believe me, I'd be the first to throw out IE if that were possible, but we can't and therefore scripts have to work on it.

If I find one, I will post it. If you think I'm wrong, please let me know. Tried this on two machines with IE, and a friend tried it on another.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <div> <blockquote> <object> <embed> <img> <param>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Copy the characters (respecting upper/lower case) from the image.