2011-09-19 28 views
0

我正在排序具有主要聯繫人姓名的對象數組等。有時這有一個空白值,當我使用下面的函數時,它將所有這些都正確地排序,但是所有的空白都在列表的頂部而不是底部。我認爲添加下面所示的條件是可行的,但事實並非如此。如何添加將所有空白條目排序到列表末尾的排序功能條件?

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

我錯過了什麼?

+0

你確定長度爲零? – epascarello

+0

(空字符串)出現在控制檯輸出中,所以是的。我認爲我做錯了什麼是使a.PrimaryContact名稱上的條件,而不是b.PrimaryContactName – Maxx

回答

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

這個'else if(a epascarello

+0

@epascarello:我喜歡對稱,你不喜歡,所以放鬆一下。 –

+1

@epascarello:當你提出的修改不是空字符串時,完全錯過了'a == b'的情況。事實證明,我的*無用的*'返回0'畢竟沒有那麼無用。調整第一個「if」將是一個選擇,但我又喜歡對稱。 –

1

比較函數必須是反射的,傳遞的和反對稱的。您的功能不符合這些標準。例如,如果兩個空白條目相互比較,則必須返回0,而不是-1。

0

返回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;如果b出現在b之後,則返回1。

查看MDN sort doco瞭解更多信息。

+1

這仍然違反反身性。兩個空白條目必須相等。 –

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; 
} 
相關問題