找到开始和结束时间数组之间的间隔的最佳方法是什么

时间:2016-02-12 05:42:38

标签: javascript arrays

我有startTime和endTime的数组。我想从间隔数组中找到实际的开始时间和结束时间。该数组如下所示。

var shiftArray = [{"startTime":"14:00:00","endTime":"21:59:59"},
                  {"startTime":"06:00:00","endTime":"13:59:59"},
                  {"startTime":"22:00:00","endTime":"05:59:59"}];

预期结果是:

todayShift = {"startTime":"06:00:00", "endTime":"05:59:59"};

任何人都可以建议一些最佳选择来达到预期效果。

1 个答案:

答案 0 :(得分:0)

我认为除了循环和比较之外还有其他方法



var shiftArray = [{
  "startTime": "14:00:00",
  "endTime": "21:59:59"
}, {
  "startTime": "06:00:00",
  "endTime": "13:59:59"
}, {
  "startTime": "22:00:00",
  "endTime": "05:59:59"
}];
var todayShift = {
  "startTime": "23:59:59",
  "endTime": "00:00:00"
};
shiftArray.forEach(function(shift) {
  if (shift.startTime < todayShift.startTime) {
    todayShift.startTime = shift.startTime;
  }
  if (shift.endTime > todayShift.endTime) {
    todayShift.endTime = shift.endTime;
  }
})
result.innerHTML = JSON.stringify(todayShift, null, 2)
&#13;
<pre id="result"></pre>
&#13;
&#13;
&#13;