skip to Main Content

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?

2

Answers


  1. 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; }
    
    Login or Signup to reply.
    1. Using name remove is misleading and doesn’t match other array methods, I would suggest removeAt or removeIndex or even popAt
    2. Assigning to the prototype creates an enumerable property, in rare cases (when someone uses for .. in on an array) it will cause run-time crashes. So define it properly as non enumerable
    3. The whole idea doesn’t make sense since there’s already a standard Array#splice for the same operation
    Object.defineProperty(Array.prototype, 'removeAt', {value: function (index) {
      return this.splice(index, 1)[0];
    }, configurable: true})
    
    const arr = [1,2,3,4,5];
    
    const result = arr.removeAt(2);
    
    console.log(arr, result);

    The same using Array#splice:

    const arr = [1,2,3,4,5];
    
    const [result] = arr.splice(2, 1);
    
    console.log(arr, result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search