Get the Last Item of an Array Using Node.js
Do you want to know how to get the last item in an array in Node.js?
You need to get the index of the last value in the array. And you can get that index value dynamically with this method:
By using that method, you can get the index of the last value of an array even if you don't know the
length beforehand. The index of the last item is simply the length of the array subtracted by
Let's go over a quick example.
Given this array of 5 different string items named
const myArray = ["Arbys", "McDonalds", "Wendys", "Taco Bell", "Chick-fil-A"]
You can get the last value of this array of delicious food establishments with this method:
const lastItem = myArray[myArray.length - 1]
myArray.length - 1 method comes out to
4 in this case, which is the index of the last value. If you
console.log() the lastItem variable, the
"Chick-fil-A" string value will be logged.
Try this out with arrays that have varying lengths and see that the solution works in all cases.
Hopefully, this was helpful in your coding endeavors.
Thanks for reading and happy coding!