0

How to remove an element of an array and have that removed element saved in a variable:

var item = arr.remove(index)
Aurimas
  • 2,577
  • 5
  • 26
  • 37

3 Answers3

4

You can use Array.prototype.splice for this purpose:

const arr = ['a', 'b', 'c'];
const removed = arr.splice(1, 1).pop();
console.log(arr) // ['a', 'c'];
console.log(removed) // 'b'

Note that in the example above, splice is chained with Array.prototype.pop - that's because splice, as mentioned by @Andreas, always returns an Array, so pop is used to extract the single value from Array returned by splice.

antonku
  • 7,377
  • 2
  • 15
  • 21
  • Thanks! Doesn't `.pop()` return the last item in array? how does this work? – Aurimas Jan 12 '19 at 17:44
  • 2
    @Aurimas You are right, `pop` returns the last item in an array. And we are good with it, since previous `splice` method call returned an array that contains only a single value. When you are calling `pop` on an array that has a single value - this single value is being returned. – antonku Jan 12 '19 at 17:48
2

What you're looking for is splice. This takes as parameters the index of the item to remove, and the count of items from that to take out. Because you only want to remove 1 item, the 2nd parameter will always be 1. Splice also returns as an array, so we're indexing that [0] to get just the contents.

var arr = ['a','b','c'];
var item = arr.splice(1,1)[0]; // 'b'
GenericUser
  • 3,003
  • 1
  • 11
  • 17
0

Maybe something like this?

Array.prototype.remove=function(i){
    var item=this[i]
    this.splice(i,1)
    return item
}

arr=[1,2,3]
item=arr.remove(1)
console.log(item) //2
console.log(arr) //[1,3]

I hope that this will help you!

FZs
  • 16,581
  • 13
  • 41
  • 50
  • 1
    [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – str Jan 12 '19 at 17:36
  • 1
    `var item = ...` + `return item` are not necessary as `.splice()` does already return the removed item(s). – Andreas Jan 12 '19 at 17:41