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
Using the
splice
method on the array to remove one item on thatindex
.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
As @jsejcksn shared, for Typescript
remove
is misleading and doesn’t match other array methods, I would suggestremoveAt
orremoveIndex
or evenpopAt
for .. in
on an array) it will cause run-time crashes. So define it properly as non enumerableArray#splice
for the same operationThe same using
Array#splice
: