在 Meteor 中按升序排序 return

Sort return by ascending order in Meteor

在 Meteor 中使用映射函数后,我无法确定排序需要存在的位置。我希望能够得到返回的结果,并按升序显示。 Meteor API 文档对排序说明符的描述比较浅显。

Template.foodList.helpers({
  foodCounts: function() {
    return _.map(_.countBy(Foods.find().fetch(), 'text'), function(value, key){
      return {text: key, count: value};
    });
   }
});

因为 _.countBy 操纵数据的顺序,您需要在之后进行排序。可能最好也排在 _.map 之后。

Template.foodList.helpers({
  foodCounts: function() {
    var data = _.map(_.countBy(Foods.find().fetch(), 'text'), function(value, key){
          return {text: key, count: value};
    });
    // sort by `text` field
    return _.sortBy(data, function(datum){ 
           return datum.text.toLowerCase(); 
    });
  }
});

Template.foodList.helpers({
  foodCounts: function() {
    var data = _.map(_.countBy(Foods.find().fetch(), 'text'), function(value, key){
          return {text: key, count: value};
    });
    // sort by count
    return _.sortBy(data, function(datum){ 
           return datum.count; 
    });
  }
});

这是一个使用下划线和链接的简短解决方案:

Template.foodList.helpers({
  foodCounts: function() {
    return _.chain(Foods.find().fetch())
      .countBy('text')
      .map(function(v, k) {return {text: k, count: v};})
      .sortBy('count')
      .value();
  }
});