Select

Again, ES5 has a utility function filter() for reducing arrays:

var result = []
for (var i=0; i < array.length; i++)
  if (array[i].name == "test")
    result.push(array[i])

result = array.filter(function(item, i){
  return item.name == "test"
});

CoffeeScript’s basic syntax uses the when keyword to filter items with a comparison. Behind the scenes, a for loop is generated. The whole execution is performed in an anonymous function to ward against scope leakage and variable conflict:

result = (item for item in array when item.name is "test")

Don’t forget to include the parens, as otherwise result will be the last item in the array. CoffeeScript’s comprehensions are so flexible that they allow you to do powerful selections as in the following example:

passed = []
failed = []
(if score > 60 then passed else failed).push score for score in [49, 58, 76, 82, 88, 90]

# Or
passed = (score for score in scores when score > 60)

If comprehensions get too long, you can split them onto multiple lines:

passed = []
failed = []
for score in [49, 58, 76, 82, 88, 90]
  (if score > 60 then passed else failed).push score

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.