-
Website
http://paulmwatson.com/journal -
Original page
http://paulmwatson.com/journal/2006/07/13/remove-array-item/ -
Subscribe
All Comments -
Community
-
Top Commenters
-
aidanf
1 comment · 3 points
-
keithbohanna
1 comment · 1 points
-
martinmurphy
1 comment · 1 points
-
jufemaiz
1 comment · 1 points
-
lxsg
1 comment · 1 points
-
-
Popular Threads
And I reckon it could be used, just use this = this.filter(func);.
Maybe you could do this.clear and then this.push(this.filter blah blah
Array.prototype.remove = function(item_to_remove)
{
var index;
while((index = this.indexOf(item_to_remove)) != -1)
{
this.splice(index, 1);
}
}
That'll remove all of the items that match. For instance:
var filtered = [1, 2, 3, 4, 5, 6, 5, 7, 8, 5, 9, 10];
filtered.remove(5);
document.write(filtered);
1,2,3,4,6,7,8,9,10
Array.prototype.remove = function(item_to_remove)
{
var index;
while((index = this.indexOf(item_to_remove)) != -1)
{
this.splice(index, 1);
}
return this;
}
That way you can do:
var filtered = [1, 2, 3, 4, 5, 6, 5, 7, 8, 5, 9, 10].remove(5);
document.write(filtered);
I'm not sure if javascript also has them, but a couple of other useful Python functions on sequences are map and reduce, which behave like:
def map(fn, list):
newlist = []
for item in list:
newlist.append = fn(item)
def reduce(fn ,list, initial_arg = None):
if initial_arg:
val = initial_arg
start = 0
else:
val = list[0]
start = 1
for i in range(start, len(list)):
val = fn(val, myseq[i])
return val
I may have goofed these up as I did them off the top of my head, but hopefully you get the idea.