25

I need the same result as:

var array = [1, 2, 3, 5, 7];
var top = array.pop();

The problem is that pop removes the element from the array. To fix that I added another line:

array.push(top);

But it is annoying me, I did it four or five times in this project till now. Is there a better way?

Washington Guedes
  • 4,254
  • 3
  • 30
  • 56
  • 12
    `array[array.length-1]` – Rayon Jun 30 '16 at 15:50
  • 2
    Please search before asking. It's impossible to not fall on an answer. – Denys Séguret Jun 30 '16 at 15:52
  • 4
    In addition to ```array[array.length-1]```, you can try ```const top = array.slice(-1).pop()``` or ```const top = array.slice(-1)[0]``` The original array will not be modified. (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) – Yuci Jan 02 '19 at 17:48

4 Answers4

25

When grabbing from the end you can do array[array.length - x], where x is the number of items from the end you wanna grab.

For instance, to grab the last item you would use array[array.length - 1].

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
Michael Jones
  • 2,222
  • 18
  • 32
  • Extending the array prototype might have been the worst thing you could have done in that scenario :( But but but - I bet you've learned a lot since this q! – The Dembinski Nov 08 '18 at 21:25
  • This worked for me. I still wanted the array to contain the last value but I wanted to check the status of that value. – Nik Hammer-Ellis Jan 30 '19 at 18:25
  • 4
    so much typing. I also looked this question up because I didn't want to type array.length -1 – James Joshua Street Jul 31 '19 at 06:30
  • 6
    @JamesJoshuaStreet same here, it would be great to have native methods like `Array.prototype.first()` and `Array.prototype.last()` corresponding to `shift()` and `pop()` respectively. Of course, typing `array[0]` is shorter than `array.first()` but the latter clearly shows the intent. And of course, `last()` will still be shorter. – Jay Dadhania Dec 13 '19 at 00:01
  • Yes. I am using react and I need to type `this.props.array[this.props.array.length-1]` – The gates of Zion Feb 06 '22 at 11:34
7

I would suggest: array[array.length-1]

The Dembinski
  • 1,469
  • 1
  • 15
  • 24
3

You can get the arr.length starting from the end such as: arr[arr.length -1]

Bruno,

Bruno Barbosa
  • 94
  • 1
  • 7
2
var array = [1, 2, 3, 5, 7];
var lastItem = array[array.length - 1]
NTL
  • 997
  • 7
  • 15