idea: Array.prototype.remove

# #!/JoePea (5 years ago)

I sometimes find myself doing things like

this.children.splice(this.children.indexOf(child), 1)

but it seems that it will iterate the array twice. Maybe a new method can be introduced so engines can optimize it:

this.children.remove(child)
// or
this.children.remove(...childrenToRemove)
# Jordan Harband (5 years ago)

Why "remove" and not .filter, to produce a new array?

# Isiah Meadows (5 years ago)

The proposed remove here is actually in-place. And this really is not unlike this proposal of mine 1, which is also in place.

The reason it belongs in the standard library is because you can optimize it way better using vector instructions and it's among one of the most common cases for .filter - how often have you done array.filter(x => x !== value)? With my Array.prototype.delete,

you could do array.slice().delete(value, true) for practically the same thing (it's 3 extra characters), just done a bit faster thanks to not needing the overhead.

  • For deleting a single value* from a dense array, you could optimize it much like array.indexOf followed by array.copyWithin + array.length -= 1 if the value exists.
  • For deleting multiple values* from a dense array, you'd do it similarly, just you'd keep a separate offset that you'd increment on each hit, subtracting that for the stores.
  • In each case, your search would be a mix of SIMD with horizontal reductions, things most modern processors make easy.
  • With a few exceptions, of course. Doubles in V8 and 32-bit SpiderMonkey are one of them, since they are boxed and compared by their contents. Multi-character strings are another big exception.

The reason I called mine delete instead of remove is to align with Set.prototype.delete and Map.prototype.delete, which operate similarly.


Isiah Meadows contact at isiahmeadows.com, www.isiahmeadows.com