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; | |
} | |
}; |
Merged!
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);
I'll add the first one back as well, with that note. Thanks for reminding...I noticed it and forgot to mention it.
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];
You can merge it manually by checking out your gist via git and merging my fork, [email protected]:1787122.git