Get the last element in an array of objects?

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

I have an array of objects in my JavaScript code.

It looks similar to this:

[
  {id: 1, username: "example"},
  {id: 2, username: "example"},
  {id: 3, username: "example"},
  {id: 4, username: "example"},
  {id: 5, username: "example"}
]

How would I get the last element in that array?

5 suggested answers
itsbambi on Jan 20

Your fastest options will be either:

array[array.length - 1]

Or the slice() method:

array.slice(-1)[0]
0 replies
itsbambi on Jan 20

Using Lodash:

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

If you don't mine using jQuery, they provide an easy method:

$(array).get(-1)
0 replies
yaboy01 on Jan 20

You can use slice():

array.slice(-1)[0]

And you could also use slice() alongside pop():

array.slice(-1).pop()
0 replies
moon_man41 on Jan 20

The most efficient options in terms of speed are these two:

array.slice(-1)[0]

array[array.length - 1]

But here are some other options you could use:

// pop()
array.pop()

[...array].pop()

// lodash
_.last(array)

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

// reverse()
array.reverse()[0]

// reduceRight()
array.reduceRight(a => a)

// splice()
let [last] = array.splice(-1)
0 replies
Answered