Get the last element in an array of strings?

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

In my JavaScript code, I have an array of strings similar to this:

["username1", "username2", "username3"]

How do I get the last element in that array?

5 suggested answers
yaboy01 on Jan 20
array[array.length - 1]

This gets the element at the last index position in the array (i.e. length - 1).

0 replies
moon_man41 on Jan 20 · Edited
array.slice(-1)[0]

slice(-1) returns the last element in the array. And [0] returns the element value.

You can also use pop():

array.slice(-1).pop()
0 replies
timmy123 on Jan 20 · Edited
var array = ["username1", "username2", "username3"]

var lastItem = array.pop() // "username3"

Notice: This will remove the last item from your original array.

0 replies
rusty1_rusty1 on Jan 20

Lodash has the last() method you can use:

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

The fastest methods:

array[array.length - 1]

array.slice(-1)[0]

Other methods:

Pop():

array.pop()

[...array].pop()

reduceRight():

array.reduceRight(a => a)

splice():

let [last] = array.splice(-1)

reverse():

array.reverse()[0]

Lodash:

_.last(array)

jQuery:

$(array).get(-1)
0 replies
Answered