Using a Javascript for loop to extract the initial event date from a Google Calendar

In my home.html file, the script below is responsible for:

  • Connecting the website to a Google Calendar API
  • Fetching dates and names of rocket launches

My concern arises when a calendar for the same rocket has multiple launches in a single month. I aim for the loop to only add the next upcoming launch/event instead of just the last one by skipping all previous entries.

Any suggestions or advice would be greatly appreciated!

Below is the data extracted from the Google Calendar API.

Array(25)
0
: 
{name: '(NET) Hanbit-TLV  • Test Flight', eventdate: '12/15/2022 12:00 AM'}
1
: 
{name: '(NET) Kestrel I • Test Flight', eventdate: '12/15/2022 11:00 PM'}
2
: 
{name: 'Long March CZ-11 • Shenjian 2013', eventdate: '12/16/2022 6:00 AM'}
3
: 
{name: 'Falcon 9 B5 • SWOT', eventdate: '12/16/2022 11:46 AM'}
4
: 
{name: 'Falcon 9 B5 • O3b mPOWER 1–2', eventdate: '12/16/2022 9:21 PM'}
5
: 
{name: 'Falcon 9 B5 • Starlink 3557–3610', eventdate: '12/16/2022 9:54 PM'}
6
: 
{name: 'Electron • Hawk 6A/B/C', eventdate: '12/16/2022 11:00 PM'}
7
: 
{name: 'Vega C • Pléiades Neo 5–6', eventdate: '12/20/2022 1:47 AM'}
8
: 
{name: '(NET) Terran 1 • Test Flight', eventdate: '12/25/2022 12:00 AM'}
9
:
... (the list continues)

(index):561
Array(5)
0
: 
{name: 'Electron', eventdate: '12/16/2022 11:00 PM'}
1
: 
{name: 'Falcon 9 B5', eventdate: '01/01/2023 12:00 AM'}
2
: 
{name: 'New Shepard', eventdate: ''}
3
: 
{name: 'SpaceShipTwo', eventdate: ''}
4
:
{name: 'Gaofen 14', eventdate: ''}
<!DOCTYPE html>
<html lang="en">

{% load static %}
{%include "Base.html"%}

<!-- Cache Eraser -->
...

Answer №1

I have modified the if statement to take into account the startDate of the event and to update existing events with the earliest startDate.

.then(function (response) {
if (response.result.items) {
  var calendarRows = ['<table class="wellness-calendar"><tbody>'];
  var events = [];
  var startsAt, endsAt;
  var startDate, endDate;
  response.result.items.forEach(function (entry) {
    startDate = entry.start.dateTime || entry.start.date;
    endDate = entry.end.dateTime || entry.end.date;

    if (startDate) {
      startsAt = moment.utc(startDate).format("L") + ' ' + moment.utc(startDate).format("LT");
    }
    if (endDate) {
      endsAt = moment.utc(endDate).format("L") + ' ' + moment.utc(endDate).format("LT");
    }

    calendarRows.push(`<tr><td>${startsAt} - ${endsAt}</td><td>${entry.summary}</td></tr>`);

    console.log(entry.summary);
    if (entry.summary) {
      const ev = {
        "name": entry.summary,
        "eventdate": startsAt,
        "start": startDate,
        "end": endDate,    
      }

      const exIndex = events.findIndex(e => e.name == ev.name);
      if(exIndex) {
        if(events[exIndex].start > ev.start) {
          events[exIndex] = ev;
        }
      } else {
        events.push(ev);
      }
    }
  });
  console.log(events);
  setAllEvenDates(events);
  console.log(arrElements);
  setAllInterval();
  calendarRows.push('</tbody></table>');
  $('#wellness-calendar').html(calendarRows.join(""));
}

Answer №2

give this a shot

gapi.client.init({
    'apiKey': apiKey,
    'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
}).then(function() {
    return gapi.client.calendar.events.list({
        'calendarId': calendarId,
        'timeZone': userTimeZone,
        'singleEvents': true,
        'timeMin': (new Date()).toISOString(), //fetches only future events
        'maxResults': 25,
        'orderBy': 'startTime'
    });
}).then(function(response) {
    if (response.result.items) {
        var displayRows = ['<table class="wellness-calendar"><tbody>'];
        var eventsList = [];
        var startTime, endTime;
        var eventStartDate, eventEndDate;
        response.result.items.forEach(function(entry) {
            eventStartDate = entry.start.date || entry.start.dateTime;
            eventEndDate = entry.end.date || entry.end.dateTime;

            if (eventStartDate) {
                startTime = moment.utc(eventStartDate).format("L") + ' ' + moment.utc(eventStartDate).format("LT");
            }
            if (eventEndDate) {
                endTime = moment.utc(eventEndDate).format("L") + ' ' + moment.utc(eventEndDate).format("LT");
            }

            displayRows.push(`<tr><td>${startTime} - ${endTime}</td><td>${entry.summary}</td></tr>`);
            
            const eventName = ["Electron", "Falcon 9 B5", "New Shepard", "SpaceShipTwo", "Gaofen 14"].find(item => entry.summary.search(item) !== -1)
            
            if (eventName) {
                const eventData = {
                    "name": eventName,
                    "eventdate": startTime,
                    "start": eventStartDate
                }

                const existingIndex = eventsList.findIndex(e => e.name == eventData.name);

                if (existingIndex !== -1) {
                    if (moment.utc(eventsList[existingIndex].start).isAfter(moment.utc(eventData.start))) {
                        eventsList[existingIndex] = eventData;
                    }
                } else if (moment.utc(eventData.start).isAfter(moment.utc())) {
                    eventsList.push(eventData);
                }
            }
        });
    }
})

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

What is the best way to experiment with angular-ui-tinymce within a tabset using Plunker?

I am currently experimenting with angular-ui-tinymce by incorporating it into a Plunkr. Can anyone assist me in integrating the necessary files for angular-ui-tinymce into the Plunkr so that I can showcase its functionality? Currently, I have this Plunker ...

Double-reading the request body in Golang

type ValidationModel struct { Name string `json:"name" valid:"alpha,required~Name is required"` Email string `json:"email" valid:"email~Enter a valid email.,required~Email is required."` Password string `json:"password" valid:"required~P ...

The current layout of the div is hindering the ability to switch from vertical scrolling to horizontal scrolling

I'm currently utilizing this scroll converter tool to transform vertical scrolling into horizontal scrolling. However, despite correct script inclusion and initialization, the conversion is not working as expected. It seems like there might be an issu ...

Could you provide some advice for creating a Single Page website?

I am working on a simple HTML setup with various elements such as a navbar and content blocks. <html> <head> <title>My HTML5 App</title> <meta charset="UTF-8"> <meta name="viewport" content="wid ...

What is the best way to iterate through an object and retrieve the following 3 items using a for loop in JavaScript

After fetching data from a website and storing it in a variable, I have successfully implemented a for loop that returns 3 properties from the object every time a button is clicked. However, the issue arises as the same data is returned with each button c ...

I'm curious about the safety and effectiveness of using a Json object to submit form data. Currently, I'm utilizing MVC 2 in conjunction with JQuery

Recently in my ASP.Net MVC 2 project, I have incorporated the use of a Json object for submitting form data. I am now seeking insights from experts on whether this approach is considered safe and recommended, and why. To clarify, I am not asking for tech ...

Convert HTML code into a customized JSON structure

Is there a way to convert HTML into a specific JSON object? For instance This HTML page is well-structured (originally in markdown). I am interested in creating a JSON version of the different sections present on the page. In this scenario, every "h2" s ...

What is the best method for retrieving a local value in Javascript?

Consider a scenario where there exists a variable named animationComplete (which is part of a 3rd-party library) and a function called happenAfterAnimation: An easy solution would involve the following code snippet: while(!animationComplete) { // Do n ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

The filter method in combination with slice array functions is not functioning properly

My search input is used to filter an array of users displayed in a table. The table has pagination set up so that only 10 users are shown per page. Oddly enough, the search filter only seems to work on the first page. Once I navigate to another page, the ...

Adjust the text color based on the background image or color

Here on this site, I have designed the first div to display a dark image, while the second one shows a light background. I am aiming to adjust the sidebar text color based on whether it is displayed against the dark or light background. How can I achieve ...

Display various post types in a WordPress loop

I am designing a website on Wordpress where I want to showcase various "tiles" containing content from different sections of the site on the homepage. These tiles are custom post types such as "services", "consultants", and "blog posts". While I understan ...

Dealing with excessively large data for json_encode in PHP

In my Symfony project, I am facing an issue while trying to retrieve database data through AJAX. Specifically, when attempting to json_encode all estimates from our database (over 60k in total), I encounter an out of memory error. Interestingly, if I try t ...

Authenticate yourself as a user or an organization on mongodb

I am currently developing an application that requires user registration and login, as well as organization registration and login. I have implemented the use of Node.js Passport with a local strategy for authentication. While I have successfully created t ...

Testing the mongoose.connect callback method in Jest: A step-by-step guide

Currently working on a new Express application and utilizing Jest as the testing framework. All sections of code have been successfully covered, except for the callback of the mongoose.connect method: https://i.sstatic.net/SNrep.png I attempted to spy o ...

Execute the function numerous times that is associated with an asynchronous function in JavaScript

I am currently working on two functions: one is asynchronous as it fetches data from a CSV file, and the other function renders a list of cities. The CSV file contains information about shops located in various cities. My goal is to display a list of cit ...

Processing JSON data using specific fields in .Net (C#)

Currently working on an application that retrieves a list of objects in JSON format: [ { "ObjectType": "apple", "ObjectSize": 35, "ObjectCost": 4, "ObjectTaste": "good", "ObjectColor": "golden" }, { "Obje ...

Developing an interactive input field using JavaScript's Document Object Model (DOM)

I am struggling with creating an editable text field using JavaScript. I have come across a function that allows for editing, but I am unsure if it is possible to change the title from High School to Middle School, which is generated by the function create ...

The combination of Three.js and React

Hello everyone! I am completely new to Three.js and I'm currently attempting to integrate it with React. While looking for resources, I came across this helpful medium article on the topic: Starting with React 16 and Three.js in 5 minutes My goal is ...

Utilizing Loopback Callbacks within a Looping Structure

While working in a for-loop, I encountered an issue where I needed to access the loop variable 'i' from within a callback function but it was not accessible due to closure restrictions. Despite attempting different methods such as using (i) or ca ...