What is the opposite of the JavaScript push();
method?
Say I had an array:
var exampleArray = ['remove'];
I want to push();
the word 'keep'
-
exampleArray.push('keep');
How do I delete the string 'remove'
from the array?
push()
adds at end; pop()
deletes from end.
unshift()
adds to front; shift()
deletes from front.
splice()
can do whatever it wants, wherever it wants.
Well, you've kind of asked two questions. The opposite of push()
(as the question is titled) is pop()
.
var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);
exampleArray.pop();
console.log(exampleArray);
pop()
will remove the last element from exampleArray
and return that element ("hi") but it will not delete the string "myName" from the array because "myName" is not the last element.
What you need is shift()
or splice()
:
var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);
exampleArray.shift();
console.log(exampleArray);
var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);
exampleArray.splice(0, 1);
console.log(exampleArray);
For more array methods, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods
pop()
does NOT remove the last element from an array. Just that it wouldn't remove the first element myName
in the array ['myName', 'hi']
, which is what @AlexSafayan wants to do.
Sep 15, 2015 at 16:54
var array = [2, 5, 9]; var index = array.indexOf(5);
Note: browser support for indexOf is limited; it is not supported in Internet Explorer 7 and 8. Then remove it with splice:if (index > -1) { array.splice(index, 1); }