Extract a free hour from the JavaScript time array without any filtering

In my Javascript array, I have the teaching schedule of a teacher for the day.

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

My goal is to determine the free hours in the above array between 10 AM and 6 PM.

The output array will be structured as follows:

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

I would appreciate your assistance in solving this problem.

Answer №1

By comparing the end time of one object with the start time of the next object, I make a decision on whether to include it in my free time.

Here is a JavaScript code snippet that implements this comparison:

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)

Answer №2

Give this method a try

var data = {
  "schedule": [{
      "start": "10:00",
      "end": "11:00"
    },
    {
      "start": "12:00",
      "end": "01:00"
    },
    {
      "start": "04:00",
      "end": "06:00"
    }
  ]
};
var convertTime = (time) => {
  time = Number(time.replace(":", "."));
  time += time < 10 ? 12 : 0;
  return time;
};

var output = data.schedule.map(item => [convertTime(item.start), convertTime(item.end)])
  .reduce((acc, current, index, array) => {
    if(index < array.length - 1) {
      acc.push([current[1], array[index + 1][0]]);
    }
    return acc;
  }, []).map(segment => ({
    start: segment[0],
    end: segment[1]
  }));

console.log(output);

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

How can you access the query in Next.js API when req.query is initially set to undefined?

Is there a way to compare the value of req.query with the cookies on the site, even when req.query is undefined upon initial load? How can this be addressed? export default async function handler(req, res) { const { method } = req; const userId = req ...

Populate the text box with database values using the first text box entry

Is it possible to automatically fill in textbox values from a database based on the input entered in another text box? For example, when I enter a name, can the Date of Birth be retrieved and populated in the corresponding field? I attempted to follow an ...

Filtering data dynamically in a nested array of objects using JavaScript

My task involves utilizing a dynamic array named var arr = ["key1","key2","key3"]. The goal is to filter an array of objects using this array. Here’s an example: var obj = [{"key1":{"key2":{"key3":5}}},{"key1":{"key2":{"key3":7}}},{"key1":{"key2":{"key3 ...

Utilize the API to seamlessly integrate a new contact into your Pushbullet account

Struggling to include a new contact in my Pushbullet contacts list through the API. I'm sending this json data in my POST request to { "name": "some name", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcbda ...

Updating data scope in AngularJS using $http request not functioning properly

I am facing an issue where the $scope.user_free_status is not updating when I set a user free, but works perfectly fine when I unset the parameter. It's strange that I need to reload the page in one case and not the other. The data fetched is stored i ...

Struggling to understand what's causing this JSON parsing issue

Currently, I am facing a challenge in my Android application where I need to display JSON data from a Webserver in a ListView. While the app successfully receives the data, it encounters an issue when trying to process it for display. The specific error m ...

Tips for querying Mongo using Node.js

Although this question may seem repetitive, please bear with me. My goal is to query MongoDB directly from the dom eventually, but for now, I'm working on querying from my routes module. Below is my query: var db = require('./config/db.js&apos ...

The responseXML received from an Ajax/POST request is missing only when using Chrome browser

While working on a "simple" JavaScript application, I noticed an unusual behavior. A function in the script sends a request with parameters to a .php page using the traditional Ajax/POST method. function sendRequest(params, doAsync, onSending, onDone) { v ...

How can I showcase Blob /JSON data in Liferay 7.2?

I am currently working with a service builder that efficiently retrieves form data from a MySQL database. One of the fields contains JSON data, and I attempted to map it using an object mapper library called com.fasterxml.jackson.databind.ObjectMapper in o ...

Having issues with UTF8 encoding when utilizing AJAX to send the complete HTML source in JavaScript

I'm encountering difficulties when trying to send a complete page source using AJAX. Despite attempting to escape the content with escape(), encodeURI(), and encodeURIComponent(), I cannot successfully transmit utf8 characters. Below is my code snipp ...

Troubleshooting the issue of onclick not functioning in JavaScript

My attempt to utilize onclick to trigger a function when the user clicks the button doesn't seem to be successful. For instance: function click(){ console.log('you click it!') } <input type='button' id='submitbutto ...

Is it possible to develop in React without using webpack, relying solely on Gulp instead?

Although I appreciate some aspects of Webpack, my enthusiasm for it wanes as the configuration files grow beyond 15 lines. It becomes overly cryptic, difficult to configure, and time-consuming. Therefore, I tend to reserve its use for just a couple of task ...

Concealing website links in the browser's address bar

Running my own website on a personal server with Ubuntu server, I noticed that my public IP address is displayed in the status bar when visitors browse my site or hover over links. Even after purchasing a domain name from godaddy, I couldn't find an o ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...

Revoking existing Json Web Tokens when updating user information

Once a user logs in with their username and password, they receive an access_token containing the payload that includes their uniqueTokenIdentifier. This unique identifier is stored for each user in the database. If a user changes their password due to ac ...

Issues encountered while using Arraylist in C

Currently, I am working on a program to create an arraylist (dynamic array) in C. Progress is good, with about 70-80% completion. However, I encountered a major issue when testing the code on different machines. To explain further, I added a series of str ...

No IOException was found in the variable e

Related Question: Exception is NULL always I'm facing an unusual issue involving an IOException object that I haven't been able to resolve. The code in question is as follows: try { // This section may not be critical, but it could be rela ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

Components in array not displaying in React

I've been struggling to generate a table from an array in React. Typically, I retrieve data from a database, but for testing purposes, I manually created the array to ensure the data is correct. Despite following examples by enclosing my map code with ...

"Launching a node server in Azure to get you up and running

Currently, I have a Single Page Application that is hosted on Microsoft Azure. This application requires refreshing some dashboard data every 5 seconds. To achieve this, I have developed a nodejs service that continuously requests data from the API and gen ...