Ignoring the First Element When Looping an Array in CoffeeScript
I really like CoffeeScript's expressive for-loop. Instead of initializing an index and then incrementing it as you loop through, CoffeeScript's for-loop, by default, serves the same purpose as a foreach loop in other languages, such as C#.
However, you can't skip the first element without doing a check. Fortunately, JavaScript's Array object has a built-in slice
method that will provide you with an array with elements removed.
Hence, we can use it to ignore the first element.
for el in arr.slice(1)
console.log el
As a corollary, you can also ignore the last element as well.
for el in arr.slice(0, arr.length - 1)
console.log el
Written by Salehen Shovon Rahman
Related protips
2 Responses
You can also use:
https://gist.github.com/a4f7fb6f15010891aeea
For more CoffeeScript magic!
over 1 year ago
·
@chorvus thanks a lot for that.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
iam4x
94.17K
ericdfields
63.02K
Related Tags
#coffeescript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#