按多个字段对集合进行排序

时间:2014-02-05 17:21:49

标签: javascript sorting backbone.js collections

如何通过两个属性对集合的模型进行排序?

这是我到目前为止所做的:

 Character = Backbone.Model.extend();

 Characters = Backbone.Collection.extend({
     model: Character,
     comparator: function(character){
         return [character.get('children') != undefined, character.get('age')]
     }
 });

 var myCharacters = new Characters([
     { name: 'Cersei',   age: 32, children: 3 },
     { name: 'Aemon',    age: 100             },
     { name: 'Tyrion',   age: 24              },
     { name: 'Stannis',  age: 33, children: 1 },
     { name: 'Daenerys', age: 14              }
     { name: 'Tywin',    age: 54, children: 3 },
     { name: 'Arya',     age: 9               },
 ]);

 myCharacters.sort;

模型应按children排序(他们是否有孩子),然后按age(从最老到最小)排序。 由此产生的顺序是:Tywin,Stannis,Cersei,Aemon,Tyrion,Daenerys,Arya

3 个答案:

答案 0 :(得分:1)

好的,我明白了。

 Characters = Backbone.Collection.extend({
     model: Character,
     comparator: function(c){
         return [c.get('children') ? 0 : 1, 1/c.get('age')];
    }
 });

sort方法从最小值到最大值排序 如果角色有孩子,比较器将返回[0, (1/age)]
否则(没有孩子)它将返回[1, (1/age)]

字符的排序方式如下:

 Tywin    [0, 0.019]  
 Stannis  [0, 0.030]  
 Cersei   [0, 0.031]  
 Aemon    [1, 0.010]  
 Tyrion   [1, 0.042]  
 Daenerys [1, 0.071]  
 Arya     [1, 0.111]

答案 1 :(得分:0)

你的comparator函数需要接受参数(a,b)并返回

  • -1如果a在b
  • 之前
  • 0如果相等
  • 1,如果b在
  • 之前

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Fsort

答案 2 :(得分:0)

试试这个。

比较器:function(char1,char2){

     var child1 = char1.get("children");
    var child2 = char2.get('children');
    var ageDiff = char1.get("age") - char1.get("age");
    if(child1 && child2){
        var diff = child1 - child2;
        if(diff !=0) return diff;
        return  ageDiff;
    }
    if(!child1 && !child2) return ageDiff;
    if(child1) return 1;
    return -1;
}