Thursday, March 4, 2010

Removing item with given value from an Array in Javascript

'Delete' operator is the easiest way to remove from Javascript's array elements with given index. It works fine with objects like literals but using it on arrays is worst thing you can ever do. What happens if you try?

var tab = [1,2,3];
delete tab[1];
//result: [1, undefined, 3]

It just removes particular element, not even try to fix undefined space left after the operation. So its better to use splice() instead.

var tab = [1,2,3];
tab.splice(1, 1);
// result: [1, 3]

Okey, but what to do if we have to remove item with some given value? We can google a little and find how to expand prototype of an Array object with remove() method, like that:

Array.prototype.remove = function(value) {
this.splice(this.indexOf(value), 1);
return true;
};
a=[112, 234, 32545];
a.remove(234);
// a is [112, 32545];

It works for that case, for sure, but what when item we try to find is not in our array? indexOf() will return -1, and splice() will start to removing elements from end of an array.

a=[112, 234, 32545];
a.remove(22);
//a is [112, 234]

Not funny. So to avoid situations like that we have to put one additional condition to our method.

Array.prototype.remove = function(value) {
if (this.indexOf(value)!==-1) {
this.splice(this.indexOf(value), 1);
return true;
} else {
return false;
};
}

a=[112, 234, 32545];
a.remove(234);
// [112, 32545];
a.remove(22);
// still [112, 32545];

Everything's fine. But in IE (there is always some 'but' in there, thanks Bill), for sure in 6.0, i don't know about new versions, Array type Objects have no indexOf() method, so we have to build it on our own:

if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i < this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
};
}


Now it works fine. Thanks.

5 comments: