Iterate over the JSON data and evaluate the timestamps for comparison

I am attempting to iterate through this JSON data and compare the "start_time" and "end_time" values to ensure that there are no overlaps. However, I am struggling to implement this functionality.

While researching, I came across a resource on how to validate two time ranges in JavaScript at validate two times, but it does not directly address my JSON structure. Would it be possible to use jQuery for this task?

{
    "Line_1":{
        "artist":"Audien",
        "day":"1",
        "start_time":"13:00",
        "end_time":"14:00",
        "stage":"main"
    },
    "Line_2":{
        "artist":"Slushii",
        "day":"1",
        "start_time":"13:30",
        "end_time":"14:30",
        "stage":"eclipse"
    },
    "Line_3":{
        "artist":"DJ Snake",
        "day":"1",
        "start_time":"15:00",
        "end_time":"16:00",
        "stage":"main"
    },
    "Line_4":{
        "artist":"Marshmello",
        "day":"2",
        "start_time":"14:15",
        "end_time":"15:15",
        "stage":"horizon"
    }
}

Expected outcome:

Audien & Slushii Conflict!

DJ Snake Does not Conflict with anyone!

Marshmello Does not Conflict with anyone!

*Please note the different days specified (Day 1 & Day 2)

Answer №1

Here is a detailed example for educational purposes. It utilizes moment.js and twix.js.

See Demo: https://jsfiddle.net/JAAulde/5v7yksk3/4/

HTML snippet for prototype code:

<ul id="output"></ul>

Javascript for prototype code

var data = {
        "Line_1":{
            "artist":"Audien",
            "day":"1",
            "start_time":"13:00",
            "end_time":"14:00",
            "stage":"main"
        },
        "Line_2":{
            "artist":"Slushii",
            "day":"1",
            "start_time":"13:30",
            "end_time":"14:30",
            "stage":"eclipse"
        },
        "Line_3":{
            "artist":"DJ Snake",
            "day":"1",
            "start_time":"15:00",
            "end_time":"16:00",
            "stage":"main"
        },
        "Line_4":{
            "artist":"Marshmello",
            "day":"2",
            "start_time":"14:15",
            "end_time":"15:15",
            "stage":"horizon"
        }
        
    },
    tmp_day = '2000-01-01',
    outer_key,
    outer,
    inner_key,
    inner,
    tmp_range,
    checked = {},
    conflict_found = {},
    conflicts = [],
    i;

for (outer_key in data) {
    if (Object.prototype.hasOwnProperty.call(data, outer_key)) {
        outer = data[outer_key];

        tmp_range = moment(tmp_day + 'T' + outer.start_time).twix(tmp_day + 'T' + outer.end_time);

        checked[outer_key] = true;

        for (inner_key in data) {
            if (Object.prototype.hasOwnProperty.call(data, inner_key) && 
                outer_key !== inner_key &&
                !checked[inner_key]
            ) {
                inner = data[inner_key];

                if (outer.day === inner.day &&
                    (
                        tmp_range.contains(tmp_day + 'T' + inner.start_time) ||
                        tmp_range.contains(tmp_day + 'T' + inner.end_time)
                    )
                ) {
                    conflict_found[outer_key] = true;
                    conflict_found[inner_key] = true;

                    conflicts.push([
                        outer_key,
                        inner_key
                    ]);
                }
            }
        }
    }
}

// Output:
document.getElementById('output').innerHTML = '';

for (i = 0; i < conflicts.length; i++) {
    document.getElementById('output').innerHTML += '<li><strong>' + data[conflicts[i][0]].artist + '</strong> conflicts with <strong>' + data[conflicts[i][1]].artist + '</strong></li>';
}

for (outer_key in data) {
    if (Object.prototype.hasOwnProperty.call(data, outer_key) && 
        !conflict_found[outer_key]
    ) {
        document.getElementById('output').innerHTML += '<li><strong>' + data[outer_key].artist + '</strong> does not have any conflicts</li>';
    }
}

Answer №2

Here is my proposed solution:

var schedule = {
  "Line_1":{
    "artist":"Audien",
    "day":"1",
    "start_time":"13:00",
    "end_time":"14:00",
    "stage":"main"

  },
  "Line_2":{
    "artist":"Slushii",
    "day":"1","start_time":"13:30",
    "end_time":"14:30",
    "stage":"eclipse"

  },
  "Line_3":{
    "artist":"DJ Snake",
    "day":"1",
    "start_time":"15:00",
    "end_time":"16:00",
    "stage":"main"

  },
  "Line_4":{
    "artist":"Marshmello",
    "day":"2",
    "start_time":"17:15",
    "end_time":"15:15",
    "stage":"horizon"

  }
};

function convertTimeToMilliseconds(timeStr) {
    var referenceDate = '01/01/1980  '; 
    return Date.parse(referenceDate + timeStr);
}

for (item in schedule) {
    var startTime = schedule[item].start_time;
    var endTime = schedule[item].end_time;
    var areDatesCorrect = (convertTimeToMilliseconds(startTime) < convertTimeToMilliseconds(endTime)) ? 'true' : 'false';
    console.log(item + ' dates correct: ' + areDatesCorrect);
};

Check out the demo here: https://jsfiddle.net/dhf89twr/1/

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

Stopping all animations with JQuery animate()

I have a question about stopping multiple animations. Here's some pseudocode to illustrate my situation: CSS #div1 { position: absolute; background-image: url("gfx/cat.jpg"); width: 60px; height: 70px; background-size: 50%; b ...

Header Express does not contain any cookies, which may vary based on the specific path

In my express.js app, I have two controllers set up for handling requests: /auth and /posts. I've implemented token authorization to set the Authorization cookie, but I'm encountering an issue when making a request to /posts. The request goes th ...

Determine the length of the content within an HTML container that has

I am attempting to retrieve the length of the container's content in HTML dynamically. However, I am only receiving the object instead of the desired result. <script> $(document).ready(function (e) { var adsense_box_len = $(&apo ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Rendering real-time data using jQuery's Ajax functionality

Imagine having a webpage that gradually returns a large amount of data over time. Here's an example code snippet to illustrate this: <?php $iTime = time(); while(time()-$iTime < 10 ) { echo "Hello world"; echo str_repeat( ' &apos ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Tips for returning an element to its starting position following animation

Hey there, I’m fairly new to the world of HTML and CSS. Recently, I was working on creating a YouTube clone website and I’ve run into an issue with the navigation. On the official YouTube website, when you click on the hamburger menu icon, the naviga ...

Limit the input to a specific format

Currently developing a JavaScript application, but having some confusion with Regular Expressions. The main goal is to allow users to input a specific format of strings in a text area for the application to process accordingly, thus requiring restriction o ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

Dealing with issues regarding the rendering of events in FullCalendar when utilizing the .getJSON() method from

I'm facing some difficulties when trying to render an event in the month view of FullCalendar. Below is the code snippet that makes a .getJSON call from the razor page, followed by the JsonResult returned by the controller and the object displayed in ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

React powered interactive tables

I am in the process of creating a dynamic table using React, and here is the data structure I am working with: { numRows: 2, numCols: 3, cells: [ { id: 1, pos: { row: 1, col: 1 }, content: 'This is th ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Retrieve information from deeply nested JSON and showcase using Vue-Multiselect

My goal is to fetch data from the server and present it in Multiselect using nested JSON, which can be done through Vue-Multiselect. Once displayed, I should have the ability to add new tags as needed, essentially updating the data. While I can display o ...

Manipulating multidimensional arrays in PHP and converting them to JSON format

I have a MySQL table with the following fields: id | building | title | parent Now, I am looking to implement a timeline calendar using fullcalendar.io. This is the structure I aim to create: { id: '1', building: '460 Bryant', title ...

Improving performance of a lengthy select query to generate JSON output in a Rails application

Trying to efficiently retrieve and format a significant amount of data from various database tables into nested JSON for quick output on the browser has been a top priority. Experimenting with different methods to streamline this process, I've experim ...