2013-04-15 74 views
0

我有,我用它來按日期的事件進行排序的功能:按日期排序,然後定位

function SortByDateAsc() { 

    return function (a,b) { 

     var aDate = new Date(new Date(a['Month'] +" "+ a['Day']+ " "+ a['Year'])); 
     var bDate = new Date(new Date(b['Month'] +" "+ b['Day']+ " "+ b['Year'])); 

     return (aDate < bDate) ? -1 : (aDate > bDate) ? 1 : 0; 

    } 
} 

如果我想按日期排序,然後按位置例如我有兩個結果相同的日期,但他們在兩個不同的位置。我將如何添加要按字母順序排序的位置?

那麼我的最終結果應該是日期加上字母順序的位置?

回答

3

在返回0之前爲該位置添加類似檢查。而且,創建日期的方式也不那麼複雜。

function SortByDateAsc() { 
    return function (a,b) { 
    // the month-1 is because Date months are 0-indexed, which 
    // might not be necessary if your months are already 0-indexes 
    var aDate = new Date(a.Year, a.Month-1, a.Day).getTime(); 
    var bDate = new Date(b.Year, b.Month-1, b.Day).getTime(); 

    return (aDate < bDate) ? -1 : (aDate > bDate) ? 1 : someLocationComparator(a,b); 
    } 
} 

請仔細閱讀the Date docs

+0

感謝這個:-) – Jerome

+0

完美地工作。如果你的問題就解決了,你介意[接受回答?(http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) –

1

返回值將告訴系統您想要的順序。

如果你想兩個相同日期的事件進行排序只是不上的排序函數返回0:

function SortByDateAsc() { 
    return function (a,b) { 

     var aDate = new Date(new Date(a['Month'] +" "+ a['Day']+ " "+ a['Year'])); 
     var bDate = new Date(new Date(b['Month'] +" "+ b['Day']+ " "+ b['Year'])); 

     var diff = aDate - bDate; 
     if (diff !== 0) 
      return diff; 

     return (a.location < b.location) ? -1 : (a.location > b.location) ? 1 : 0; 
    } 
} 
相關問題