How to remove an element of an array and have that removed element saved in a variable:
var item = arr.remove(index)
How to remove an element of an array and have that removed element saved in a variable:
var item = arr.remove(index)
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
.
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'
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!