2016-07-31 63 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,如果你希望看到它的行动。

相关问题