Reputation: 19133
I am sorting a dictionary using the following coffeescript
sortList: (list) ->
keys = Object.keys(list).sort (a, b) -> list[b] - list[a]
for name in keys
{name, count: list[name]} if list[name] > 1
This produces an array where each item that has list[name] > 1
is represented by a void value. You can see why if you look at the transpiled JS
FilterService.prototype.sortList = function(list) {
var keys, name, _i, _len, _results;
keys = Object.keys(list).sort(function(a, b) {
return list[b] - list[a];
});
_results = [];
for (_i = 0, _len = keys.length; _i < _len; _i++) {
name = keys[_i];
if (list[name] > 1) {
_results.push({
name: name,
count: list[name]
});
} else {
_results.push(void 0); <-- See the unwanted else clause here
}
}
return _results;
};
I can get the result I want if I include a dummy else
clause myself, like this:
sortList: (list) ->
keys = Object.keys(list).sort (a, b) -> list[b] - list[a]
for name in keys
if list[name] > 1
{name, count: list[name]}
else
Now the unwanted generated else
clause is empty and the resulting array does not contain any elements for list[name] > 1
Can you tell me how to correctly prevent the filtered items from appearing in the resulting array?
Thanks
Upvotes: 1
Views: 69
Reputation: 6069
What about filtering with the when
keyword?
class StackExchange
sortList: (list) ->
keys = Object.keys(list).sort (a, b) -> list[b] - list[a]
({name, count: list[name]} for name in keys when list[name] > 1)
transpiles to
StackExchange.prototype.sortList = function(list) {
var keys, name, _i, _len, _results;
keys = Object.keys(list).sort(function(a, b) {
return list[b] - list[a];
});
_results = [];
for (_i = 0, _len = keys.length; _i < _len; _i++) {
name = keys[_i];
if (list[name] > 1) {
_results.push({
name: name,
count: list[name]
});
}
}
return _results;
};
Upvotes: 2