2016-07-31 113 views
0

我有開始和結束時間的對象的列表:排序開始時間,打破結束時間關係

let times = [ 
    {start: moment().add(1, 'days'), end: moment().add(2, 'days')}, 
    {start: moment().add(1, 'days'), end: moment().add(2, 'days')}, 
    {start: moment().add(4, 'days'), end: moment().add(5, 'days')}, 
    {start: moment().add(1, 'days'), end: moment().add(7, 'days')}, 
    {start: moment().add(2, 'days'), end: moment().add(3, 'days')}, 
] 

我想這些時間由開始時間排序(最早到最晚),同時打破與結束時間的關係(首先是較短的結束時間)。

所以結果應該是這樣的:

let sortedTimes = [ 
    {start: moment().add(1, 'days'), end: moment().add(2, 'days')}, 
    {start: moment().add(1, 'days'), end: moment().add(2, 'days')}, 
    {start: moment().add(1, 'days'), end: moment().add(7, 'days')}, 
    {start: moment().add(2, 'days'), end: moment().add(3, 'days')}, 
    {start: moment().add(4, 'days'), end: moment().add(5, 'days')}, 
] 

是否有一個首選的JavaScript的方式與高階函數/最小的語法來做到這一點?我開始寫一個腳本,但邏輯包含很多if - else if - else語法,想知道是否有更好的方法。再次感謝!

回答

2

從外觀上來看,我假設你正在使用moment.js。這不利用高階函數,而只是使用Array.prototype.sort方法使用自定義比較功能和語法是非常簡潔:

times.sort(function(a, b) { 
    return a.start.isBefore(b.start) ? -1 : a.start.isSame(b.start) ? a.end.isBefore(b.end) ? -1 : 1 : 1; 
}); 

寫到:

times.sort(function(a, b) { 
    if (a.start.isBefore(b.start)) { 
     return -1; // a before b 
    } else if (a.start.isSame(b.start)) { 
     // break tie on end 
     if (a.end.isBefore(b.end)) { 
      return -1; // a before b 
     } else { 
      return 1; // b before a 
     } 
    } else { 
     return 1; // b before a 
    } 
} 

這裏有一個plunkr,如果你希望看到它的行動。

相關問題