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]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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,
If you don’t want the array modified,
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 thanlast = 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.