I have a list of array items like this:
const items = [
{ a: 1 },
{ b: 2 },
{ c: 3 },
]
How can I return / log the last element: { c: 3 }
Here's what I've tried so far:
let newarray = items.map((item) => {
console.log(item);
})
console.log(newarray);
You can use the Array.at() method, which was moved to Stage 4 in Aug, 2021.
['a','b','c'].at(-1) // 'c'
This is often referred to as relative indexing which...
takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
Docs
Stack Overflow
just log the length minus 1, nothing to do with es6:
console.log(items[items.length - 1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With