Reputation: 35
I have a time range, for example: 14:30:00 until 18:30:00. Consider this time range somebody's work shift. During this time range, they state they cannot work from 15:30:00 until 16:30:00 and from 17:30:00 until 18:30:00.
var obj = {
startTime: 14:30,
endTime: 18:30
}
var deviation = [{s:15:30,e:16:30},{s:17:30,e:18:30}]
So i need output like
[{s:14:30 ,e:15:30}, {s:15:30,e:16:30}, {s:16:30,e:17:30}, {s:17:30,e:18:30}]
Upvotes: 1
Views: 741
Reputation: 2587
You can do it by concatenating your start time, end time with a sorted deviation array. Create an array from that concatenated array.
var obj = {
startTime: '14:30',
endTime: '18:30'
}
var deviation = [{s:'15:30',e:'16:30'},{s:'16:30',e:'18:30'}]
function intervals(obj,deviation){
// sort deviation according to starting time of deviations
deviation.sort((a,b)=>{
return a.s < b.s ? -1 : 1 ;
})
if(deviation[0].s >= obj.startTime && deviation[deviation.length - 1].e <= obj.endTime){
let ans = [];
ans = deviation.reduce((acc,val)=>{
return acc.concat( val.s, val.e);
},[]);
// check if starttime and minimum time deviation is not same.
if(ans[0] != obj.startTime){
ans.unshift(obj.startTime);
}
// check if endtime and maximum time in deviation is not same.
if(ans[ans.length - 1]!=obj.endTime){
ans.push(obj.endTime);
}
let temp = [];
// create an array of objects from sorted list ans;
for(let i = 0; i < ans.length; i++){
if(i+1 < ans.length){
if(ans[i]!=ans[i+1]){
temp.push({
s: ans[i],
e: ans[i+1]
});
}
}
}
return temp;
}
else{
console.log("Invalid values of deviation.");
}
}
console.log(intervals(obj,deviation));
Upvotes: 1
Reputation: 424
I has created an example as you want. I think code is something tough and long so if it helpful for you then use otherwise ignore it.
var obj = {
s: '14:30',
e: '18:30'
}
var deviation = [{
s: '15:30',
e: '16:30'
},
{
s: '17:30',
e: '18:30'
}]
$(document).ready(function () {
deviation.push(obj);
var newArr = [];
$(deviation).each(function (index, value) {
newArr.push(value.e);
newArr.push(value.s);
});
var newArr = newArr.sort();
var $timeArr = [];
lastVal = '';
$(newArr).each(function (index, value) {
if (index == 0) {
lastVal = value;
} else {
var stTime = lastVal;
var endTime = value;
lastVal = endTime;
var pushObj = {
s: stTime,
e: endTime
}
var lsstKey = newArr.length - 1;
if (index != lsstKey) {
$timeArr.push(pushObj);
}
}
});
document.getElementById("myarray").innerHTML = JSON.stringify($timeArr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="myarray"></p>
Please check in below link
https://jsfiddle.net/vinay_kaklotar/vbt1uspe/3/
Upvotes: 2