Skip to content

Instantly share code, notes, and snippets.

@gigafied
Forked from dlo/README.md
Created February 10, 2012 06:12
Show Gist options
  • Save gigafied/1787122 to your computer and use it in GitHub Desktop.
Save gigafied/1787122 to your computer and use it in GitHub Desktop.
Array.remove prototype function

This is a small snippet that gives Javascript arrays the (much-needed) ability to remove elements based on value. Example:

items = [1,2,3,3,4,4,5];
items.remove(3); // => [1,2,4,4,5]
Array.prototype.remove = function(elem) {
var ai = this.indexOf(elem);
while(ai > -1){
this.splice(ai,1);
ai = this.indexOf(elem);
}
return this;
};
@gigafied
Copy link
Author

One thing to note, is that this modifies the original array, whereas your method returns a new array.

Your way:

var items = [1,2,3,3,4,4,5];
items.remove(3); // => [1,2,4,4,5]
items; // => [1,2,3,3,4,4,5];

My way:

var items = [1,2,3,3,4,4,5];
items.remove(3); // => [1,2,4,4,5]
items; // => [1,2,4,4,5]

To get my way working like yours you would have to copy the array first, via slice or concat:

items.slice(0).remove(3);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment