Clean way to remove element from javascript array

2019-01-13 02:10发布

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.

8条回答
Emotional °昔
2楼-- · 2019-01-13 02:54

This is just a slight change to Amir's awesome solution:

Array::remove = (e) -> @splice(t,1)[0] if (t = @indexOf(e)) > -1

which returns the element iff the list has it, so you can do something like:

do_something 100 if a.remove(100)

The remove coffee script translates to this javascript:

Array.prototype.remove = function(e) {
  var t, _ref;
  if ((t = this.indexOf(e)) > -1) {
    return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
  }};
查看更多
祖国的老花朵
3楼-- · 2019-01-13 02:56

Using vanilla Javascript:

Array.prototype.remove = function(elem) {
    var match = -1;

    while( (match = this.indexOf(elem)) > -1 ) {
        this.splice(match, 1);
    }
};

var a = [4, 8, 2, 3];

a.remove(8);

Only jQuery:

jQuery.removeFromArray = function(value, arr) {
    return jQuery.grep(arr, function(elem, index) {
        return elem !== value;
    });
};

var a = [4, 8, 2, 3];

a = jQuery.removeFromArray(8, a);
查看更多
登录 后发表回答