Get the last element in an array?

Answered
suparman21 asked this question 4 months ago
suparman21 on Jan 19

How do I get the last element in a JavaScript array?

This may be a string or an object.

Is there a simple way to do this?

Thanks in advance!

6 suggested answers
looper003 on Jan 20

Here are the fastest options:

array.slice(-1)[0]

array[array.length - 1]

Both of those will get you the last item in your array.

Here are some additional methods:

// lodash
_.last(array)

// jQuery
$(array).get(-1)

// splice()
let [last] = array.splice(-1)
0 replies
moon_man41 on Jan 20
array.slice(-1)[0]
0 replies
nick on Jan 20
array[array.length - 1]
0 replies
yaboy01 on Jan 20

Lodash:

_.last(array)
0 replies
coderguy on Jan 20

jQuery:

$(yourArray).get(-1)
0 replies
softwareguy411 on Jan 20

Using pop():

array.pop()

[...array].pop()

Reminder: this method will remove the element from your array.

0 replies
Answered