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.

9 comments:

  1. Nice trick... I hadn't thought to use indexOf with splice, that works a lot better than delete for long-living arrays. Thanks.

    ReplyDelete
  2. thanks for sharing, I'm completing the matrix multiplication of two-dimensional case. and this reference is very helpful in completing my tasks

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. This works me in AngularJS for deleting specific records Delete record in AngularJS with ng-repeat

    Hope you enjoy reading it

    ReplyDelete
  6. This is a good post. This post give truly quality information. I’m definitely going to look into it. Really very useful tips are provided here. thank you so much. Keep up the good works.
    AWS Training in pune
    AWS Online Training

    ReplyDelete
  7. This is a great post and example on how to use Splice() in JavaScript. Thank you for sharing!

    ReplyDelete