Remove a value from an array in CoffeeScript
filter()
is also an option:
arr = [..., "Hello", "World", "Again", ...]newArr = arr.filter (word) -> word isnt "World"
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.
For this is such a natural need, I often prototype my arrays with an remove(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"]