Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the get the last element in an array items using JavaScript

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);
like image 918
baiju thomas Avatar asked Jun 04 '26 06:06

baiju thomas


2 Answers

Update 2021+

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.

Further Reading

  • Docs

    • MDN - Array.prototype.at()
    • Proposal - Relative Indexing Method
    • tc39 spec - Array.at
    • CanIUse - JavaScript built-in: Array: at
  • Stack Overflow

    • Get the last item in an array
    • Selecting last element in JavaScript array
    • Destructuring to get the last element of an array in es6
like image 153
KyleMit Avatar answered Jun 05 '26 20:06

KyleMit


just log the length minus 1, nothing to do with es6:

console.log(items[items.length - 1])
like image 44
bryan60 Avatar answered Jun 05 '26 18:06

bryan60