200

I need help on this problem - 'What is the opposite of the JavaScript push(); method?'

Like say I had a array -

var exampleArray = ['remove'];

I want to push(); the word 'keep' -

exampleArray.push('keep');

How do I delete the string 'remove' from the array?

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
Alex
  • 2,571
  • 4
  • 13
  • 22
  • 1
    `shift` or `splice`. – elclanrs Aug 27 '14 at 01:37
  • Don't mind giving an example? – Alex Aug 27 '14 at 01:38
  • 4
    You can find a list if all array methods in the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array – Felix Kling Aug 27 '14 at 01:38
  • 2
    Other dups http://stackoverflow.com/questions/4644139/to-remove-first-and-last-element-in-array-using-jquery, http://stackoverflow.com/questions/19544452/remove-last-item-from-array – elclanrs Aug 27 '14 at 01:39
  • First, find the index of the element you want to remove: `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); }` – Anand Singh Feb 21 '18 at 07:59
  • `[].pop` could be used! –  Jan 20 '19 at 05:21

2 Answers2

152

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.

Amadan
  • 169,219
  • 18
  • 195
  • 256
135

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

Travis Hohl
  • 1,986
  • 2
  • 12
  • 15
  • `pop` does remove the (last) element from the array – jasonscript Aug 27 '14 at 03:43
  • @jasonscript: You're right -- revised my definition of pop() so that it's more clear. – Travis Hohl Aug 27 '14 at 11:42
  • @jasonscript: For the record, I never suggested `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. – Travis Hohl Sep 15 '15 at 16:54