JS Built-ins
← Array218 / 226
ArrayArray.prototype.withintermediate

Replace Last Element

πŸ“– Usage Example
const arr = ['a', 'b', 'c']
arr.with(-1, 'z')  // β†’ ['a', 'b', 'z']
arr                // β†’ ['a', 'b', 'c']  (unchanged)

Pass a negative index to with() to replace an element counting from the end.

Array.prototype.with β€” Negative Index

with() supports negative indices. -1 refers to the last element.

Implement replaceFromEnd that replaces the last element of arr with val using arr.with(-1, val).

πŸ’‘ Hints (2)
  • β€’ Negative indices in `with()` count from the end of the array.
  • β€’ `-1` is the last element, `-2` is second-to-last, etc.