37

The CoffeeScript docs state that list comprehensions should be able to do the select/filter operations:

They should be able to handle most places where you otherwise would use a loop, each/forEach, map, or select/filter.

You'd imagine you could do something in one line like result = item for item in list if item % 2 == 0 However the closest I can come is

list = [1,2,3,4]
result = []
for item in list
  if item % 2 == 0 then result.push item

Whats the most concise way to filter a list in CoffeeScript?

2 Answers 2

79
result = (item for item in list when item % 2 == 0)

edit : added result =

1
  • 3
    Put that in a function, otherwise, it does nothing. Type it into "Try Coffeescript" in jashkenas.github.com/coffee-script and look at the javascript output.
    – Amir
    Jan 30, 2011 at 3:02
8

Unless you are trying to squeeze every ounce of performance out, I would create a filter function like this:

filter = (list, func) -> x for x in list when func(x)

or if you want to add it to the prototype of every array:

Array::filter = (func) -> x for x in @ when func(x)

and then write: (respectively)

result = filter mylist, (x) -> x % 2 == 0

or

result = mylist.filter (x) -> x % 2 == 0

For reference, this is the javascript that gets generated:

var filter, result;
filter = function(list, func) {
    var x, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = list.length; _i < _len; _i++) {
        x = list[_i];
        if (func(x)) {
            _results.push(x);
        }
    }
    return _results;
};
Array.prototype.filter = function(func) {
    var x, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = this.length; _i < _len; _i++) {
        x = this[_i];
        if (func(x)) {
            _results.push(x);
        }
    }
    return _results;
};
result = filter(mylist, function(x) {
    return x % 2 === 0;
});
result = mylist.filter(function(x) {
    return x % 2 === 0;
});

There is a similar question here

2
  • 1
    Its definitely a matter of personal preference as they both get the job done - but taking python as an example, list comprehensions are generally preferred over functional programming functions when possible since they are considered more readable. Jan 31, 2011 at 1:40
  • 1
    wat. Array already has this exact function… (just maybe more efficient) Oct 10, 2012 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.