There are many questions about this, not least: jQuery version of array contains, a solution with the splice method and many more. However, they all seem complicated and annoying.
With the combined powers of javascript, jQuery and coffeescript, what is the very cleanest way to remove an element from a javascript array? We don't know the index in advance. In code:
a = [4,8,2,3]
a.remove(8) # a is now [4,2,3]
Failing a good built-in method, what is a clean way of extending javascript arrays to support such a method? If it helps, I'm really using arrays as sets. Solutions will ideally work nicely in coffeescript with jQuery support. Also, I couldn't care less about speed, but instead prioritize clear, simple code.
CoffeeScript:
Which simply splices out the element at position
t
, the index wheree
was found (if it was actually foundt > -1
). Coffeescript translates this to:And if you want to remove all matching elements, and return a new array, using CoffeeScript and jQuery:
which translates into:
Or doing the same without jQuery's grep:
which translates to:
This seems pretty clean and understandable; unlike other answers, it takes into account the possibility of an element showing up more than once.
In CoffeeScript:
Although you are asking for a clean approach using Coffeescript or jQuery, I find the cleanest approach is using the vanilla javascript method filter:
It looks cleaner in coffeescript but this translates to the exact same javascript, so I only consider it a visual difference, and not an advanced feature of coffeescript:
Filter is not supported in legacy browsers, but Mozilla provides a polyfill that adheres to the ECMA standard. I think this is a perfectly safe approach because you are only bringing old browsers to modern standards, and you are not inventing any new functionality in your polyfill.
Sorry if you were specifically looking for a jQuery or Coffeescript only method, but I think you were mainly asking for a library method because you were unaware of a clean javascript only method.
There you have it, no libraries needed!
You might just try jQuery's grep utility:
There may be a performance issue here, as you're technically causing the variable to reference a new array; you're not really modifying the original one. Assuming the original isn't referenced somewhere else, the garbage collector should take or this pretty quickly. This has never been an issue for me, but others might know better. Cheers!
This is really easy with jQuery:
Notes:
splice
returns the elements that were removed, so don't domyArray = myArray.splice()
.myArray.splice(index,1)
means "remove the array element at index'index'
from the array".$.inArray
returns the index in the array of the value you're looking for, or -1 if the value isn't in the array.if you are also using CoffeeScript creator's underscore.js library, here's a one-liner that will work nicely:
or in js: