参考
https://exceptionshub.com/remove-a-value-from-an-array-in-coffeescript.html
Answers:
array.indexOf("World")
will get the index of"World"
or-1
if it doesn’t exist.array.splice(indexOfWorld, 1)
will remove"World"
from the array.
Answers:
filter()
is also an option:
arr = [..., "Hello", "World", "Again", ...]
newArr = arr.filter (word) -> word isnt "World"
Answers:
For this is such a natural need, I often prototype my arrays with anremove(args...)
method.
My suggestion is to write this somewhere:
Array.prototype.remove = (args...) ->
output = []
for arg in args
index = @indexOf arg
output.push @splice(index, 1) if index isnt -1
output = output[0] if args.length is 1
output
And use like this anywhere:
array = [..., "Hello", "World", "Again", ...]
ref = array.remove("World")
alert array # [..., "Hello", "Again", ...]
alert ref # "World"
This way you can also remove multiple items at the same time:
array = [..., "Hello", "World", "Again", ...]
ref = array.remove("Hello", "Again")
alert array # [..., "World", ...]
alert ref # ["Hello", "Again"]
Answers:
Checking if “World” is in array:
"World" in array
Removing if exists
array = (x for x in array when x != 'World')
or
array = array.filter (e) -> e != 'World'
Keeping reference (that’s the shortest I’ve found – !.push is always false since .push > 0)
refs = []
array = array.filter (e) -> e != 'World' || !refs.push e
Answers:
Try this :
filter = ["a", "b", "c", "d", "e", "f", "g"]
#Remove "b" and "d" from the array in one go
filter.splice(index, 1) for index, value of filter when value in ["b", "d"]
Answers:
A combination of a few answers:
Array::remove = (obj) ->
@filter (el) -> el isnt obj
Answers:
_.without()
function from the underscorejs library is a good and clean option in case you want to get a new array :
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1)
[2, 3, 4]
Answers:
CoffeeScript + jQuery:
remove one, not all
arrayRemoveItemByValue = (arr,value) ->
r=$.inArray(value, arr)
unless r==-1
arr.splice(r,1)
# return
arr
console.log arrayRemoveItemByValue(['2','1','3'],'3')