Share

From this page you can share JavaScript Array Remove Method to a social bookmarking site or email a link to the page.
Social WebE-mail
Enter multiple addresses on separate lines or separate them with commas.
JavaScript Array Remove Method
(Your Name) has forwarded a page to you from Ajaxonomy
(Your Name) thought you would like to see this page from the Ajaxonomy web site.

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.