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

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -