Is there a quick (short, character wise) way to get the last element of an array (assuming the array is non-empty)?
I usually do:
last = array[array.length-1]
or last = array[-1..][0]
System. out. println(numArray[numArray. length-1]) will print the last value.
The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.
The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].
It's easy and harmless to modify the Array
prototype for this:
Array::last = -> @[@length - 1]
If you're already using the excellent Underscore.js, you can use its _.last(arr)
.
If you're using a modern version of CoffeeScript, do not use this. Use the answer by dule instead.
If you don't mind modifying the array,
last = array.pop()
If you don't want the array modified,
last = array[..].pop()
That compiles to last = array.slice(0).pop()
. I think it's pretty readable to people already exposed to CoffeeScript or Python slices. However, keep in mind that it will be much slower than last = array[array.length-1]
for large arrays.
I wouldn't recommend last = array[-1..][0]
. It's short, but I don't think its meaning is immediately obvious. It's all subjective, though.
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