ES2023 introduced Array.prototype.with
which returns a copy of the array with the element at the specified index replaced with a specified value. This is very useful when working in React or other environments where having immutable variables is important. However, there are other array mutations that one may want to perform without modifying the original array.
I would like to propose with
's counterpart, without
which would return a copy of the array with the element at the specified index removed. This would essentially be a shorthand for
myArray.filter((_, index) => index !== indexToRemove);
With an implementation of without
available, a user could equivalently write
myArray.without(indexToRemove)
which is much more concise, more clearly expresses the programmer's intent, and doesn't require the unused binding within the callback to filter
.
If desired, the implementation could also accept multiple indices to remove.
Array.prototype.without = function(...indicesToRemove) {
return this.filter((_, index) => !indicesToRemove.includes(index));
}