javascriptarraysextension-methods

How to write an extension-method in JavaScript


The following code adds a method to the Array object.

Array.prototype.remove = function (index) {
  const temp = [].concat(this);
  return [].concat(temp.slice(0, index)).concat(temp.slice(index + 1));
};

let arr = [0, 1, 2, 3, 4, 5];
console.log(arr.remove(3))

The mechanism works: the remove method returns a new array, different from the original array, in which the element placed at the index index is removed.

I would like to rewrite the remove method so that it modifies the starting array and returns the removed element, just like the Array.prototype.pop method behaves.

    Array.prototype.remove = function (index) {...};
    let arr = [0, 1, 2, 3, 4, 5];
    let removed = arr.remove(3);
    console.log({arr, removed}); // arr: [0, 1, 2, 4, 5], removed: 3

What is the technique to achieve this result?


Solution

  • Using the splice method on the array to remove one item on that index.
    The splice method will return an array with removed items ( which in our situation is is just an array with one item ), you can access the item by index 0

    Array.prototype.remove = function (index) {
      const removedItems = this.splice(index, 1);
      return removedItems[0];
    };
    

    As @jsejcksn shared, for Typescript

    interface Array<T> { remove(index: number): T | undefined; }