Mark scheduled specific time periods

I need help removing booked time slots from the total time slots. How can I achieve this?

Input:

Actual time slots:

[ '10:00-10:30',
  '10:30-11:00',
  '11:00-11:30',
  '11:30-12:00',
  '12:00-12:30',
  '12:30-13:00',
  '13:00-13:30',
  '13:30-14:00',
  '14:00-14:30',
  '14:30-15:00',
  '15:00-15:30',
  '15:30-16:00'
]

If Booked Time Slots are ["11:00-13:00", "14:00-15:00"], then the output should be:

[ '10:00-10:30',
   '10:30-11:00',
   '13:00-13:30',
   '13:30-14:00',
   '15:00-15:30',
   '15:30-16:00'
]

If Booked Time Slots is ["11:15-13:15"], then the output should be:

[ '10:00-10:30',
   '10:30-11:00',
   '13:30-14:00',
   '14:00-14:30',
   '14:30-15:00',
   '15:00-15:30',
   '15:30-16:00'
]

I attempted to solve this problem with the following code:

let actualTimeSlot = []
                            for(let i = 0; i < times_ara.length; i++) {
                                if(parseInt(times_ara[i]) < parseInt(timeBooked.split("-")[0])){
                                    actualTimeSlot.push(times_ara[i])
                                } else if(parseInt(times_ara[i]) > parseInt(timeBooked.split("-")[1])) {
                                    actualTimeSlot.push(times_ara[i])
                                } else {
                                    console.log("booked")
                                }
                            }

However, it's not working for all cases.

Answer №1

Here is a method you can use to transform your timeslots array into an array of objects using the map() function:

const ts = ['10:00-10:30','10:30-11:00','11:00-11:30','11:30-12:00','12:00-12:30','12:30-13:00','13:00-13:30','13:30-14:00','14:00-14:30','14:30-15:00','15:00-15:30','15:30-16:00'],
      booked3 = ["11:00-11:30", "13:05-13:35", "14:05-14:15"],

      avail = (ts, booked) =>
        ts.map(item => {
          const [start, end] = item.split('-'),
                isBooked = !booked
                  .map(item => item.split('-'))
                  .every(([bookedStart, bookedEnd]) => 
                    bookedStart >= end || bookedEnd <= start)
          return {slot: `${start}-${end}`, isBooked}
        })

console.log(avail(ts,booked3))
.as-console-wrapper {min-height: 100%}

Answer №2

To determine if the interval falls inside or on one of the ends, you can check its value.

function remove(from, slots) {
    return slots.reduce((r, s) => {
        var [sStart, sEnd] = s.split('-');
        return r.filter(f => {
            var [fStart, fEnd] = f.split('-');
            return (fStart < sStart || fEnd > sEnd) && (fStart > sStart || fEnd <= sStart) && (fStart >= sEnd || fEnd < sEnd);
        });
    }, from);
}

var array = ['10:00-10:30', '10:30-11:00', '11:00-11:30', '11:30-12:00', '12:00-12:30', '12:30-13:00', '13:00-13:30', '13:30-14:00', '14:00-14:30', '14:30-15:00', '15:00-15:30', '15:30-16:00'],
    result1 = remove(array, ["11:00-13:00", "14:00-15:00"]),
    result2 = remove(array, ["11:15-13:15"]);

console.log(result1);
console.log(result2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Model of Objects within a Document

Here's a puzzling question for you: why does console.log(document.body) and console.log(document.head) work perfectly fine, but console.log(document.script) or console.log(document.html) don't seem to do anything? It's strange because all of ...

Tips for Removing Copyright on Charts

Check this out : https://jsfiddle.net/oscar11/4qdan7k7/5/ Is there a way to eliminate the phrase JS chart by amCharts? ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

How to extract an inner array from a serialized string-array

Currently, I am in the process of developing a REST-API and to populate my database, I am utilizing large JSON files containing existing data. However, I have encountered an issue with deserializing one of the fields. The structure of the JSON file is as ...

The AngularJS $http.post method mimicking a successful $.ajax request is causing a 401 UNAUTHORISED error

I have been working on rewriting a functional $.ajax server call to utilize AngularJS $http.put. However, the $http method returns a 401 unauthorized error. The original ajax call I am attempting to rewrite is structured like this: $.ajax({ url: domain ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

Differences between Vue.js onMounted and watching refsVue.js offers

When it comes to calling a function that requires an HTMLElement as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting ...

JavaScript - Placing Image Caption and Details within a Box

<div id="CollectionALL"> <div id="collection1" class="col"> <img id="Img1" class="imageCS"/> <H1 id="Title1"></H1> ...

When using Angular, automatically shift focus to the next input field by pressing the

I am faced with a challenge involving multiple editable inputs on my screen. Alongside these editable inputs, there are buttons and disabled inputs present. The current behavior is such that when I press Tab, the focus shifts to the HTML elements between ...

Bringing custom JavaScript functions into a Vue.js component

In my Vue.js project, I have an abundance of Javascript processing that is all local and doesn't require server-side functionality. I'm exploring the possibility of importing a file containing specific processing functions (such as mathematical a ...

`The challenge of properly handling quotation marks within quotation marks in JavaScript string literals

I am having trouble displaying text in a JavaScript tooltip Despite my efforts to escape the quotes and eliminate any line breaks, I keep encountering unterminated string literals. The specific text I want to show is: "No, we can't. This is going t ...

Form a collection of X amount of words using a string in JavaScript

Hello amazing Stack community, I am currently striving to create a straightforward JavaScript function that can accurately count the total number of words from a given string value. Furthermore, I aim to store a specific number, X, of words into an array ...

Receive the deleted entry upon clicking the thead | Error发

Is there a way to permanently delete a row in a datatable? If I delete all the rows, I would like the datatable to display the default message of "No data available". I have attempted some POST requests : But with no success. DataTables remove row butto ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

Is there a way to efficiently retrieve and handle multiple $_POST records in PHP simultaneously?

I am currently working on developing a management interface that allows administrators to make bulk edits to members of a website all at once. While we already have the capability for single edits, there is a need for an option to modify all users simultan ...

Error message: A state has not been defined within the onload function

I'm facing an issue where I am attempting to assign a data URL of an image to a state in Vue.js, but it is not getting assigned properly. After converting a blob URL to a data URL, the state does not contain the correct data URL. While the imgSrc doe ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

What are some creative techniques for styling a JSON object for presentation?

Imagine having an array of JSON objects structured like this: [ {"id": 1234, "organization_id": 12, "name": "Susan Taylor", "created_at": 2016-07-28T05:29:25 -10:00, "role": "Admin"}, {"id": 1235, "organization_id": 12, "name": "Jeff ...

CSS responsive grid - adding a horizontal separator between rows

I currently have a responsive layout featuring a grid of content blocks. For desktop view, each row consists of 4 blocks. When viewed on a tablet, each row displays 3 blocks. On mobile devices, each row showcases 2 blocks only. I am looking to add a ho ...

The current context does not have a reference to TextBox

I am encountering an issue with my simple aspx page. Despite not using Master Content Page, I am seeing the following error: The name 'txtFirstName' does not exist in the current context Here is my Markup: <%@ Page Language="C#" %> &l ...