1

Trying to remove the last element from an array when a back button is clicked. Console is showing the correct elements in the array. it's looking like the array.slice function isn't working however I can't see why.

Code is:

$('#backButton .back').click(function(e) {
    e.preventDefault();
    answers.slice(0,-1);
    console.log(answers);
});

Answers array is showing the correct result apart from the last element in the array isn't being removed. Thanks!

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Warve
  • 481
  • 1
  • 8
  • 22

1 Answers1

4

The slice() method just returns the portion of an array it will not update the original array. You can use splice(-1, 1) or pop() method to remove the last element from array.

$('#backButton .back').click(function(e) {
     e.preventDefault();
     answers.pop();
     console.log(answers);
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188