John Resig posted a good implementation:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
If you don’t want to extend a global object, you can do something like the following, instead:
// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
But the main reason I am posting this is to warn users against the alternative implementation suggested in the comments on that page (Dec 14, 2007):
Array.prototype.remove = function(from, to){
this.splice(from, (to=[0,from||1,++to-from][arguments.length])<0?this.length+to:to);
return this.length;
};
It seems to work well at first, but through a painful process I discovered it fails when trying to remove the second to last element in an array. For example, if you have a 10-element array and you try to remove the 9th element with this:
myArray.remove(8);
You end up with an 8-element array. Don't know why but I confirmed John's original implementation doesn't have this problem.
indexOf
in IE. – Scotty.NET Sep 13 '13 at 7:48delete
should be more performant in the short term, because it won't have to shift the later items.forEach
,map
andfilter
will automatically skip processing for undefined (deleted) items. But it's probably not ideal if you will be adding a lot of things to your array in future, or reading it many times. – joeytwiddle Jul 29 at 8:55