Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first and last element of an array in CoffeeScript

If say I have an array and I would to iterate through the array, but do something different to the first and last element. How should I do that?

Taking the below code as example, how do I alert element a and e?

array = [a,b,c,d,e] for element in array   console.log(element) 

Thanks.

like image 773
revolver Avatar asked Jul 18 '12 02:07

revolver


People also ask

How do I find the first and last elements of an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.

How do you take the first element of an array?

The shift() method removes the first element from an array and returns that removed element.

How do you move the first element to the last of an array?

The shift() method removes the first item of an array. The shift() method changes the original array. The shift() method returns the shifted element.


2 Answers

You can retrieve the first and last elements by using array destructuring with a splat:

[first, ..., last] = array 

This splat usage is supported in CoffeeScript >= 1.7.0.

like image 74
Jon Gauthier Avatar answered Sep 19 '22 16:09

Jon Gauthier


The vanilla way of accessing the first and last element of an array is the same as in JS really: using the index 0 and length - 1:

console.log array[0], array[array.length - 1] 

CoffeeScript lets you write some nice array destructuring expressions:

[first, mid..., last] = array console.log first, last 

But i don't think it's worth it if you're not going to use the middle elements.

Underscore.js has some helper first and last methods that can make this more English-like (i don't want to use the phrase "self-explanatory" as i think any programmer would understand array indexing). They are easy to add to the Array objects if you don't want to use Underscore and you don't mind polluting the global namespace (this is what other libraries, like Sugar.js, do):

Array::first ?= (n) ->   if n? then @[0...(Math.max 0, n)] else @[0]  Array::last ?= (n) ->   if n? then @[(Math.max @length - n, 0)...] else @[@length - 1]  console.log array.first(), array.last() 

Update

This functions also allow you to get the n first or last elements in an array. If you don't need that functionality then the implementation would be much simpler (just the else branch basically).

Update 2

CoffeeScript >= 1.7 lets you write:

[first, ..., last] = array 

without generating an unnecessary array with the middle elements :D

like image 44
epidemian Avatar answered Sep 16 '22 16:09

epidemian