Javascript: Remove values from array prototype
In order to remove certain values or objects from an array many people iterate through it and remove unwanted occurences with the splice() method. It does what you want it to do but it’s pretty cumbersome. There are far easier and simpler ways to remove a certain value from an array.
If we have an array like so: arr = [1,2,2,3,4,5,2,6] and we’d do this: arr.remove(2) we’ll end up with [1,3,4,5,6]. Nobody likes two’s anyway.
Here is how I do it:
Array.prototype.remove = function (subject) { var r = new Array(); for(var i = 0, n = this.length; i < n; i++) { if(!(this[i]==subject)) { r[r.length] = this[i]; } } return r; }
Why is this better?
- No copy of the original is needed to do the math
- It is yet again inherently independent of other array prototypes or methods
- It runs alot faster
So there you go, another mystery solved.
Take care!
Tags: javascript, prototype, remove
That’s a nice one!
November 13th, 2008 at 5:32 pmyou’ve got a bug in your code.
January 11th, 2009 at 3:19 pmTry: arr.remove(true)
It will remove all non false values from the array. No quite what we wanted.
You need to use the identity operator === instead of ==
Good one, thanks!
@kohalza. True represents any value, so if you remove true, you remove anything that has a value in it. It is not a bug, it is a feature. As far as i know, all programming languages have this. Because true represents anything. If you do remove(false) it will remove any row with nothing in it.
So use it wisely, and correct
April 28th, 2009 at 9:17 amКрасавчег! Пиши исчё!
May 23rd, 2009 at 6:04 pmЗахватывающе. Зачет! и ниипет!
May 24th, 2009 at 5:15 pmкрасиво, сделал! Благодарю!!!
May 26th, 2009 at 6:38 amИ придратся не к чему, а я так люблю покритиковать…
May 28th, 2009 at 1:16 pmДостаточно интересная и познавательная тема
May 30th, 2009 at 9:36 pmMaybe this one will be god? It just modify existent Array obj.
Array.prototype.del = function (item) {
June 7th, 2009 at 10:11 pmthis.sort(function (a, b) {return a == item;});
var deleted = 0;
while (this[this.length-1] == item) {
this.pop();
deleted++;
}
return deleted;
}
газ и уголь в России
Занятно-занятно, нигде заранее для такое не натыкался.
September 4th, 2009 at 4:30 amКомплекс текстов хороший удачный, закину сайт в закладки!
September 14th, 2009 at 9:26 pmучастник rss
December 3rd, 2009 at 7:42 am“No copy of the original is needed to do the math”
Right before your “return r” you got one n-length array and one (n-1)length array.
It’s almost the same as having a copy of your initial array.
Except that, your method only covers the integer-indexed arrays. It’s doing its job for that, but what about hash tables?
July 30th, 2010 at 10:16 pm