0

I'm trying to remove the last item from an array, but it's not working. I did some debugging and found that array.length-1 was returning NaN for some reason. Oddly enough, array.length (without the -1) worked just fine.

lettersA.splice(lettersA.length-1); 

Any answers? (I'm using p5 in case that helps at all)

6
  • What is the real length? And the type of it? Commented Jul 20, 2017 at 20:57
  • You need to add second parameter as 1 Commented Jul 20, 2017 at 20:58
  • You can use negative index to indicate count from last like lettersA.splice(-1,1); or if its just a single element lettersA.pop(); lettersA.splice(lettersA.length-1); should also work though. Commented Jul 20, 2017 at 21:03
  • And what exactly returns NaN, your debugging, which we can't see? Please elaborate your question. Commented Jul 20, 2017 at 21:06
  • The NaN implies Not a Number - is lettersA definitely an array and not an object? Commented Jul 20, 2017 at 21:19

2 Answers 2

1

Using Array#splice in this way actually works because the start parameter is the last item, and since you've omitted the deleteCount parameter it will remove everything from start to the end of the array - the last item.

I think that the NaN you describe is cause by the return value of Array#slice. Slice returns an array that contains the deleted element(s), and you're probably trying to use this array as a number.

Example:

var lettersA = ['angel', 'clown', 'mandarin', 'sturgeon']; console.log("removed element: ", lettersA.splice(lettersA.length-1)); console.log("Array: ", lettersA);

If you want to get the removed value use Array#pop. Array#pop returns the removed element, without wrapping it in an array.

Example:

var lettersA = ['angel', 'clown', 'mandarin', 'sturgeon']; console.log("Removed element :", lettersA.pop()); console.log("Array: ", lettersA);

Sign up to request clarification or add additional context in comments.

Comments

0

As Volem said, you are missing the second parameter of splice (docs).

You can also just use pop if you are only removing one element from the end of the array (docs)

4 Comments

The rest of the arguments are optional, though.
@Teemu They are optional, but if he wants to delete the last element, it might be a little challenging without providing the deleteCount.
@eqwert - no it's not - "If deleteCount is omitted, or if its value is larger than array.length - start, then all of the elements beginning with start index on through the end of the array will be deleted."
@OriDrori Ah fair enough :) My mistake

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.