Delete value from array in CoffeeScript

I have an array:

array = [..., "Hello", "World", "Again", ...] 

How can I check if Mir is in an array? Then delete it if it exists? And is there a link to the "World"?

Sometimes, perhaps, I want to combine a word with a regular expression, in which case I will not know the exact string, so I need to have a link to the associated string. But in this case, I know for sure that this is the "World", which makes it easier.

Thanks for the suggestions. I found a cool way to do this:

http://documentcloud.github.com/underscore

+43
javascript coffeescript
Nov 20 2018-11-11T00:
source share
8 answers

array.indexOf("World") will get the index "World" or -1 if it does not exist. array.splice(indexOfWorld, 1) will remove "World" from the array.

+55
Nov 20 2018-11-11T00:
source share
β€” -

filter() also an option:

 arr = [..., "Hello", "World", "Again", ...] newArr = arr.filter (word) -> word isnt "World" 
+67
Nov 21 2018-11-11T00:
source share

This is such a natural necessity, I often prototype my arrays using the 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 this anywhere:

 array = [..., "Hello", "World", "Again", ...] ref = array.remove("World") alert array # [..., "Hello", "Again", ...] alert ref # "World" 

This way you can also delete multiple items at the same time:

 array = [..., "Hello", "World", "Again", ...] ref = array.remove("Hello", "Again") alert array # [..., "World", ...] alert ref # ["Hello", "Again"] 
+16
Dec 15 '12 at 20:09
source share

Checking for the presence of "Peace" in the array:

 "World" in array 

Delete if exists

 array = (x for x in array when x != 'World') 

or

 array = array.filter (e) -> e != 'World' 

Saving the link (which is the shortest I found - !. push is always false since .push> 0)

 refs = [] array = array.filter (e) -> e != 'World' || !refs.push e 
+14
Sep 18 '13 at 9:46 on
source share

Try the following:

 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"] 
+8
Jul 19 '12 at 20:22
source share

Combination of multiple answers:

 Array::remove = (obj) -> @filter (el) -> el isnt obj 
+2
Sep 21 '14 at 13:10
source share

_.without() function from the underscorejs library is a good and clean option if you want to get a new array:

 _.without([1, 2, 1, 0, 3, 1, 4], 0, 1) [2, 3, 4] 
+2
Nov 23 '15 at 10:58
source share

CoffeeScript + jQuery: delete 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') 
0
Sep 13 '13 at 3:06 on
source share



All Articles