Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the last element of an array in CoffeeScript

Tags:

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]

like image 291
Lchi Avatar asked Aug 22 '12 18:08

Lchi


People also ask

How do you print the last value in an array?

System. out. println(numArray[numArray. length-1]) will print the last value.

How do you check if an item is last in an array?

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.

What is the last element in an array?

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].


2 Answers

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).

like image 41
Trevor Burnham Avatar answered Sep 28 '22 02:09

Trevor Burnham


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.

like image 157
Snowball Avatar answered Sep 28 '22 01:09

Snowball