如何添加排序函数条件,将所有空白项排序到列表的末尾?

How can I add a sort function condition that will sort all the blank entries to the end of the list?

本文关键字:排序 空白 列表 何添加 添加 条件 函数      更新时间:2023-09-26

我正在排序一个对象数组,其中包含一个主要联系人姓名。有时它有一个空白值,当我使用下面的函数时,它会正确地对它进行排序,但是所有的空白都在列表的顶部而不是底部。我原以为添加如下所示的条件就可以了,但事实并非如此。

this.comparePrimaryContactName = function (a, b)
{        
     if(a.PrimaryContactName == "") return -1;
     return a.PrimaryContactName > b.PrimaryContactName ? 1 : -1;
}

我错过了什么?

我通常这样使用:

this.comparePrimaryContactName = function(a, b) {
    a = a.PrimaryContactName || '';
    b = b.PrimaryContactName || '';
    if(a.length == 0 && b.length == 0)
        return 0;
    else if(a.length == 0)  
        return 1;
    else if(b.length == 0)
        return -1;
    else if(a > b)
        return 1;
    else if(a < b)
        return -1;
    return 0;
}

比较函数必须是反射的、传递的和反对称的。你的函数不满足这些条件。例如,如果两个空白条目相互比较,则必须返回0,而不是-1。

this.comparePrimaryContactName = function (a, b)
{   
    var aName = a.PrimaryContactName;
    var bName = b.PrimaryContactName;     
    return aName === bName  ?  0 :
           aName.length===0 ? -1 :
           bName.length===0 ?  1 :
           aName > bName    ?  1 : -1;
}

对空格返回1而不是-1。

this.comparePrimaryContactName = function (a, b)  {
  if (a.PrimaryContactName == b.PrimaryContactName)
    return 0;
  if(a.PrimaryContactName == "") return 1;
  return a.PrimaryContactName > b.PrimaryContactName ? 1 : -1;
} 

如果两者相等,排序函数应该返回0,如果a在b之前,返回-1,如果a在b之后,返回1。

查看MDN排序文档获取更多信息。