使用orderBy:如何对数字数组进行排序并将任何字符串值放在底部?

时间:2016-10-31 04:09:54

标签: angularjs

我已经有一段时间了,所以我会发布我的问题和答案,万一其他人偶然发现它。

我试图按持续时间降序排列以下数组:

{
  0:
  {
    first_name: "Tom"
    duration: "00:50"
  }
  1:
  {
    first_name: "Bob"
    duration: "01:30"
  }
  2:
  {
    first_name: "Dan"
    duration: "< 1 min"
  }
}

正确的顺序应该是Bob - Tom - Dan,但是当使用AngularJS过滤器命令orderBy($scope.students,'duration',true);时,我得到了Dan - Bob - Tom。

1 个答案:

答案 0 :(得分:-1)

我解决这个问题的方法是编写一个区分唯一字符串和实际数字的函数:

var orderByExp = function(student) {
    if(student.duration.match(/\d\d:\d\d/)) {
        return student.duration;
    }
    else{
        return "";
    }
}

将该函数作为表达式传递:

orderBy($scope.students,orderByExp,true);

这样,如果我得到“xx:xx”以外的任何内容,则将其视为空字符串。