Skip to content

Instantly share code, notes, and snippets.

@dlo
Created February 10, 2012 05:54
Show Gist options
  • Select an option

  • Save dlo/1787039 to your computer and use it in GitHub Desktop.

Select an option

Save dlo/1787039 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;
};
Array.prototype.indices = function(elem) {
var indices = [];
var index = this.indexOf(elem);
while (true) {
if (index < 0) {
break;
}
else {
indices.push(index);
}
index = this.indexOf(elem, index+1);
}
return indices;
}
Array.prototype.remove = function(elem) {
var indices = this.indices(elem);
if (indices.length == 0) {
return this;
}
else {
var pos = indices[0];
var previous_pos;
var result = this.slice(0, pos);
var rest;
for (var i=1; i<indices.length; i++) {
pos = indices[i];
previous_pos = indices[i-1]
rest = this.slice(previous_pos+1, pos);
result.push.apply(result, rest);
}
rest = this.slice(pos+1)
result.push.apply(result, rest);
return result;
}
};
@gigafied

Copy link
Copy Markdown

You can merge it manually by checking out your gist via git and merging my fork, git@gist.github.com:1787122.git

@dlo

dlo commented Feb 10, 2012

Copy link
Copy Markdown
Author

Merged!

@gigafied

Copy link
Copy Markdown

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

Original:

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];

New:

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 this working like it was before, you would have to copy the array first, via slice or concat:

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

@dlo

dlo commented Feb 10, 2012

Copy link
Copy Markdown
Author

I'll add the first one back as well, with that note. Thanks for reminding...I noticed it and forgot to mention it.

@gigafied

Copy link
Copy Markdown

Of course, you could always do something like:

Array.prototype.remove = function(elem, doCopy) {
    var a = doCopy ? this.slice(0) : this;
    var ai = a.indexOf(elem);
    while(ai > -1){
        a.splice(ai,1);
        ai = a.indexOf(elem);
    }
    return a;
};

Which would give you the best of both worlds.

doCopy = false (or undefined):

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

doCopy = true:

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

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