Return the first n elements of an array in Coffeescript -
what best way return first n elements of array in coffeescript? if there fewer n elements in array, array should returned unchanged. these 2 solutions came with:
with loop , break:
arr = ["one", "two", "three", "four", "five"] n = 3 firstn = [] in [0..n-1] if arr[i] firstn.push(arr[i]) else break
with list comprehension
arr = ["one", "two", "three", "four", "five"] n = 3 firstn = (arr[i] in [0..n-1] when arr[i])
both of these work, neither clean. first not clear @ first glance. second better iterates on whole array unnecessarily , looks value twice each element in output. there better way?
use array slicing (http://coffeescript.org/#language)
arr = ["one", "two", "three", "four", "five"] arr[..2]
works want if there fewer n element in array (just returns whole array)
Comments
Post a Comment