S
Sam Collett
How do I remove an item with a specified value from an array?
i.e. array values 1,2,2,5,7,12,15,21
remove 2 from array would return
1,5,7,12,15,21
(12 and 21 are NOT removed, duplicates are also removed)
So far I have (val is value, ar is array, returns new array):
function removeFromArray(val, ar){
s = String(ar)
// remove if not first item (global search)
reRemove = new RegExp(","+val,"g")
s = s.replace(reRemove,"")
// remove if at start of array
reRemove = new RegExp("^"+val+",")
s = s.replace(reRemove,"")
// remove if only item
reRemove = new RegExp("^"+val+"$")
s = s.replace(reRemove,"")
return new Array(s)
}
However this seems to return 1,5,7,12,151 (the 151 is a result of the
',2' being removed from the '15,21' part of the array)
How would I modify this to get it to work properly (maybe as one
regular expression - broken down and explained though)?
Also I want it to work with strings as well (possibly containing
commas)
i.e.
array = "Bloggs, Jo", "Doe, John", "Doe, Jane"
remove "Doe, Jane" from array to return "Bloggs, Jo","Doe, John"
i.e. array values 1,2,2,5,7,12,15,21
remove 2 from array would return
1,5,7,12,15,21
(12 and 21 are NOT removed, duplicates are also removed)
So far I have (val is value, ar is array, returns new array):
function removeFromArray(val, ar){
s = String(ar)
// remove if not first item (global search)
reRemove = new RegExp(","+val,"g")
s = s.replace(reRemove,"")
// remove if at start of array
reRemove = new RegExp("^"+val+",")
s = s.replace(reRemove,"")
// remove if only item
reRemove = new RegExp("^"+val+"$")
s = s.replace(reRemove,"")
return new Array(s)
}
However this seems to return 1,5,7,12,151 (the 151 is a result of the
',2' being removed from the '15,21' part of the array)
How would I modify this to get it to work properly (maybe as one
regular expression - broken down and explained though)?
Also I want it to work with strings as well (possibly containing
commas)
i.e.
array = "Bloggs, Jo", "Doe, John", "Doe, Jane"
remove "Doe, Jane" from array to return "Bloggs, Jo","Doe, John"