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.
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.
The shift() method removes the first element from an array and returns that removed element.
The shift() method removes the first item of an array. The shift() method changes the original array. The shift() method returns the shifted element.
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.
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
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