DISQUS

Life is grand: Remove array item

  • David Stone · 3 years ago
    I'd tend to say that using the Array.filter method would be a cleaner way of doing it...but filter doesn't change the actual array, so you couldn't use that.
  • Paul Watson · 3 years ago
    hhmm didn't know about Array.filter. Seems quite nice, though I wonder about performance?

    And I reckon it could be used, just use this = this.filter(func);.
  • David Stone · 3 years ago
    You'd think...but setting this = this.filter... actually results in an error because you're not allowed to re-assign to this.
  • Paul Watson · 3 years ago
    Ah yeah, damn, invalid assignment. Hmmmm... So it can be used outside of a prototype extension but not inside. Grr.

    Maybe you could do this.clear and then this.push(this.filter blah blah
  • David Stone · 3 years ago
    But is that really better than the iteration and the splice?
  • David Stone · 3 years ago
    Here. This:

    Array.prototype.remove = function(item_to_remove)
    {
    var index;
    while((index = this.indexOf(item_to_remove)) != -1)
    {
    this.splice(index, 1);
    }
    }

    That'll remove all of the items that match. For instance:

    var filtered = [1, 2, 3, 4, 5, 6, 5, 7, 8, 5, 9, 10];
    filtered.remove(5);
    document.write(filtered);

    1,2,3,4,6,7,8,9,10
  • David Stone · 3 years ago
    Better:

    Array.prototype.remove = function(item_to_remove)
    {
    var index;
    while((index = this.indexOf(item_to_remove)) != -1)
    {
    this.splice(index, 1);
    }
    return this;
    }

    That way you can do:

    var filtered = [1, 2, 3, 4, 5, 6, 5, 7, 8, 5, 9, 10].remove(5);
    document.write(filtered);
  • Andrew Peace · 3 years ago
    The filter operation is quite cool - Python has something identical.

    I'm not sure if javascript also has them, but a couple of other useful Python functions on sequences are map and reduce, which behave like:


    def map(fn, list):
    newlist = []
    for item in list:
    newlist.append = fn(item)

    def reduce(fn ,list, initial_arg = None):
    if initial_arg:
    val = initial_arg
    start = 0
    else:
    val = list[0]
    start = 1

    for i in range(start, len(list)):
    val = fn(val, myseq[i])
    return val


    I may have goofed these up as I did them off the top of my head, but hopefully you get the idea.
  • Andrew Peace · 3 years ago
    Eek, that didn't look so good - not sure how to get in this message board.
  • David Stone · 3 years ago
    Andrew: Here's the JS Array Object documentation that lists what functions Array does have. As you can see, map is in there. And I think reduce is kinda like every: http://developer.mozilla.org/en/docs/Core_JavaS...
  • Paul Watson · 3 years ago
    And if it doesn't have it, prototype it :)