Answered
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?
Your fastest options will be either:
array[array.length - 1]
Or the slice()
method:
array.slice(-1)[0]
If you don't mine using jQuery, they provide an easy method:
$(array).get(-1)
You can use slice()
:
array.slice(-1)[0]
And you could also use slice()
alongside pop()
:
array.slice(-1).pop()
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)