0

I am going to create time slots of two hours each.

start_time=10:00
end_time=24:00

Like [ [10:00,12:00], [12:00,14:00], [14:00,16:00] ] ...

I am using that function:

function calculate_time_slot(start_time, end_time, interval = "120") {
    var i, formatted_time;
    var time_slots = new Array();
    for (var i = start_time; i <= end_time; i = i + interval) {
        formatted_time = convertHours(i);
        time_slots.push(formatted_time);
    }
    return time_slots;
}

but it produce results like this:

[
  '10:00', '12:00',
  '14:00', '16:00',
  '18:00', '20:00',
  '22:00', '24:00'
]

How to make the pairing like the desired results like:

[ [10:00,12:00], [12:00,14:00], [14:00,16:00] ] ...

2 Answers 2

1

Inside the loop, calculate two formatted times: one for the start of the slot, and one for the end of the slot:

function calculate_time_slot(startTime, endTime, interval = 120) {
  const timeSlots = [];
  for (let i = startTime; i < endTime; i += interval) {
    const formattedBegin = convertHours(i);
    const formattedEnd = convertHours(i + interval);
    timeSlots.push([formattedBegin, formattedEnd]);
  }
  return timeSlots;
}

Make sure to set interval to a number, not a string, so that you add instead of concatenate.

Sign up to request clarification or add additional context in comments.

3 Comments

Brilliant, Thanks for the help
Is there any way to compare two arrays like [2020-03-19, 12:30,14:00] and [2020-03-19, 12:00,14:00] and the result should be true, but as of now it is not a match but contains the similar time
@CertainPerformance You may need to return timeSlots; instead of return time_slots;.
1

You can use reduce() in the calculate_time_slot function like so:

let time_slots = ["10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00", "24:00"];

time_slots = time_slots.reduce((acc, cur, i, arr) => {
  if (i < arr.length - 1) {
    acc.push([`${cur}`, `${arr[i + 1]}`]);
  }
  return acc;
}, []);

console.log(time_slots);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.