Array.prototype.without

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));
}

You can use the toSpliced method for that:

myArray.toSpliced(indexToRemove, 1)
1 Like

Default value 1 should be there for convenience. Again no default values.

why would 1 make any sense as the default value? it's not the front, and not necessarily the back, it's just an arbitrary number. doesn't seem very convenient to me.

2 Likes

For cases like this. 1 is in most cases. It is the minimum value if you remove. Many functions have minimum values by default, for example index.

The argument is already optional, but it does not default to 1. So this can't be changed now.

If deleteCount is omitted, or if its value is greater than or equal to the number of elements after the position specified by start , then all the elements from start to the end of the array will be deleted. However, if you wish to pass any itemN parameter, you should pass Infinity as deleteCount to delete all elements after start , because an explicit undefined gets converted to 0 .