从javascript时间数组中过滤免费小时

时间:2017-11-30 11:38:19

标签: javascript arrays json

我有一个javascript数组,一天教师的教学时间

{
"time": [
  { "start":"10:00","end":"11:00" },
  { "start":"12:00","end":"01:00" },
  { "start":"04:00","end":"06:00" }
]
}

我想在上午10点到下午6点之间找出上面的免费小时

输出数组将是这样的:

{
"time": [
  { "start":"09:00","end":"10:00" },
  { "start":"11:00","end":"12:30" },
  { "start":"01:00","end":"04:00" }
]
}

请帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

我将一个对象的结尾与下一个对象的开头进行了比较;

根据他们的不同,我决定是否将其包含在空闲时间内。



let timeObj =  {
"time": [
  { "start":"10:00","end":"11:00" },
  { "start":"12:00","end":"01:00" },
  { "start":"04:00","end":"06:00" }
]
}

let newObj = {"time" : []}
let timeArr= timeObj["time"];
for(i=0;i<timeArr.length; i++) {
  if(timeArr[i+1] != undefined) {
    if(timeArr[i]["end"] != timeArr[i+1]["start"]) {
      let freetime = {
       "start" : timeArr[i]["end"],
       "end" : timeArr[i+1]["start"]
      }
      newObj["time"].push(freetime);
    }
  }
}

console.log(newObj)
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试这种方法

var obj = {
  "time": [{
      "start": "10:00",
      "end": "11:00"
    },
    {
      "start": "12:00",
      "end": "01:00"
    },
    {
      "start": "04:00",
      "end": "06:00"
    }
  ]
};
var numConvert = (t) => (t = Number(t.replace(":", ".")), t += t < 10 ? 12 : 0, t);
var output = [];
var output = obj.time.map(s => [numConvert(s.start), numConvert(s.end)])
  .reduce(function(a, b, i, arr) {
    (i < arr.length - 1) ? (a || []).push([b[1], arr[i + 1][0]]): [];
    return a;
  }, []).map(s => ({
    start: s[0],
    end: s[1]
  }));

console.log(output);