What is the best way to generate arrays of new objects by extracting objects from a current array, depending on the values within the objects themselves?

I am attempting to create new arrays of objects from an existing array called data, based on specific values within each object.

Each object represents an event and includes a startDateTime and endDateTime value in the format:

"startDateTime": "2022-10-28T21:01:11"

And

"endDateTime": "2022-10-29T21:01:11"

The goal is to have three separate arrays:

  • One for events that have already passed, identified by having endDateTime before the current date and time.
  • A second array for ongoing events, where endDateTime is after the current date and time.
  • Lastly, a third array for upcoming events, where startDateTime is after the current date and time.

To get the current date and time, I utilized the following code snippet:

var date = new Date();
var dateString =
    date.getUTCFullYear() + "-" +
    ("0" + (date.getUTCMonth()+1)).slice(-2) + "-" +
    ("0" + date.getUTCDate()).slice(-2) + "T" +
    ("0" + date.getUTCHours()).slice(-2) + ":" +
    ("0" + date.getUTCMinutes()).slice(-2) + ":" +
    ("0" + date.getUTCSeconds()).slice(-2);

console.log(dateString)
// Output example: 2022-10-28T09:00:00

The original array structure resembles the following:

const data = [
               {
                "name": "Dinner",
                "numOfAttending": 4,
                "startDateTime": "2018-04-28T19:00:00",
                "endDateTime": "2018-04-28T22:00:00"
               },
               {
                "name": "Studying",
                "numOfAttending": 1,
                "startDateTime": "2020-09-01T09:00:00",
                "endDateTime": "2023-06-10T15:00:00"
               },
               {
                "name": "Graduating!",
                "numOfAttending": 25,
                "startDateTime": "2023-06-11T09:00:00",
                "endDateTime": "2023-06-11T12:00:00"
               }
             ]

I then initialized three empty arrays to store the sorted events:

  const eventsDone = [];       // Should contain the past 'Dinner' event.
  const eventsOngoing = [];    // Should include the ongoing 'Studying' event.
  const eventsUpcoming = [];   // Should hold the upcoming 'Graduating!' event.

My attempt involved using a for loop to iterate through the original array and categorize the events based on specified conditions:

for (let i = 0; i < data.length; i++) {
    if (data[i].endDateTime < dateString) {
       eventsDone.push(data[i]);
    } 
    else if (data[i].endDateTime > dateString) {
       eventsOngoing.push(data[i]);
    }
    else if (data[i].startDateTime > dateString) {
       eventsUpcoming.push(data[i]);
    }
  }

However, I have encountered issues with this implementation.

Appreciate any assistance provided!

Answer №1

This strategy appears to be more accurate. It involves first examining the past, then looking ahead to the future (you've got that part down). Everything else is considered ongoing.

const data = [{
    "name": "Lunch",
    "numOfAttending": 2,
    "startDateTime": "2019-08-15T12:00:00",
    "endDateTime": "2019-08-15T13:00:00"
  },
  {
    "name": "Meeting",
    "numOfAttending": 6,
    "startDateTime": "2021-04-21T14:30:00",
    "endDateTime": "2021-04-21T16:00:00"
  },
  {
    "name": "Traveling",
    "numOfAttending": 3,
    "startDateTime": "2022-11-05T08:00:00",
    "endDateTime": "2022-11-08T17:00:00"
  }
]

const eventsDone = []; 
const eventsOngoing = []; 
const eventsUpcoming = [];

var currentDate = (new Date()).toISOString();
for (let i = 0; i < data.length; i++) {
  if (data[i].endDateTime < currentDate) {
    eventsDone.push(data[i]);
  } else if (data[i].startDateTime > currentDate) {
    eventsUpcoming.push(data[i]);
  } else {
    eventsOngoing.push(data[i]);
  }
}

console.log(eventsDone)
console.log(eventsOngoing)
console.log(eventsUpcoming)

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

Ensuring proper integration of this regular expression for password validation

Trying to create a jQuery function that can efficiently check if passwords meet specific requirements. The password must contain at least 3 characters that are uppercase, numbers, or special characters, in any combination. I currently have a function usi ...

Tips for retrieving multiple data outputs from an ajax success function

Within my project, I have two separate JavaScript files named myJs1.js and myJs2.js. One of the methods in myJs1.js is invoking a method from myJs2.js. My goal is to retrieve the values r1 and r2 into the results (within myJs1.js). I attempted to achiev ...

Utilizing Vue CLI plugin to dynamically pass JS variables as props

I am currently using version 4.5 of the Vue CLI plugin. I have created a component that takes in a title as a prop. This component has been converted into a web component and added to an HTML webpage (which is not a Vue JS project) Now, I am attempting to ...

By using JavaScript, you can set an onclick event on a div element to dynamically

Is there a way to load a different page when the onClick event occurs in Javascript? <div id="div_man" onclick="/subfolder/index.htm"></div> I've tried the code above, but it's not functioning correctly. Can someone please provide a ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

What is the best way to store images in a directory using JavaScript and ASP.NET?

How can I upload and save an image in a folder using ASP.NET, then call and display it? Is it possible to achieve this using AJAX, jQuery, or JavaScript with Web Method? <asp:FileUpload CssClass="image" ID="fileUpload" runat="server" /> I currently ...

Is it possible for a JSON array to consist of objects with varying key/value pairs?

Is it possible for a JSON array to contain objects with different key/value pairs? The example provided in this tutorial shows objects within the JSON array having the same key/value pair: { "example": [ { "firstName": " ...

Challenges faced with JavaScript Ajax functionality

Currently, I am developing a custom HTTP client using JavaScript. Although my code appears to be correct, I keep receiving 404 errors for my requests. This code is being executed on a NodeJS (ExpressJS) server that includes a handler as shown below: app.p ...

Identify the distinct elements within the array following content validation

Given this basic array: let result = ["doc1.rtf","doc2.rtf","test/doc4.rtf","test/doc4.rtf","test/doc6.rtf"] To find unique occurrences, you can use the following: let unique = [...new Set(result)]; This will give you: ["doc1.rtf","doc2.rtf","test/doc4.r ...

issues with responsive mobile navigation

Greetings! I've been diligently working on a website project for a client, but I have a nagging feeling that I may have overlooked something important. If you'd like to take a look at the small design mockup preview I'm providing for the cl ...

PHP displays a multi-layered array

I've been grappling with this problem for quite some time now. I have a complex array that I'm trying to format in a specific manner. Here is the structure of the array: $newArray[$counter] = $output?</p> ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

Viewing multiple pages and maintaining sessions in Laravel

I am currently working on a quiz application that involves multiple pages depending on the user's selection. However, I have encountered an issue with Laravel's pagination not saving previous page inputs. Is there a way to resolve this problem? A ...

Unable to assign the value of 'innerHTML' to a null property during an AJAX request

I have searched through numerous articles on this site, but I haven't been able to find the solution I'm looking for. Every time I click a cell in my custom div table, I receive the frustrating message "Cannot set property 'innerHTML' ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Combine each module using grunt and then compress

Looking to achieve this using Grunt. My current file structure is as follows: /app --app.js --/module1 ----module1.js ----module1Model.js --/module2 ----module2.js ----module2Model.js How can I bundle and minify each module into a single file to appear ...

How to wait for the webpage to fully load before executing a script using a Chrome extension

After opening a new website tab, I am attempting to select a DOM element by its class name. The issue I have encountered is not knowing how to effectively wait until the entire page has finished loading. Despite trying various methods such as alarms, setTi ...

What is causing the error message of "prop id does not match the rendered server output" to appear on my screen?

https://i.stack.imgur.com/VOLDT.png I've been working on a nextjs redux project and I keep running into this error whenever I refresh my page. Despite searching for a solution, I haven't been able to resolve it. The official next js blog suggest ...

What is the best way to display text on all cards when hovering over them with the cursor?

I've been attempting to make all three cards reveal text upon hovering over them with the mouse pointer. However, I'm facing an issue where only the text in the first card on the left is displayed, while the other two cards remain unaffected, des ...

Making modifications to the CSS within an embedded iframe webpage

Assigned with the task of implementing a specific method on a SharePoint 2013 site. Let's dive in. Situation: - Within a page on a SharePoint 2013 site, there is a "content editor" web part that displays a page from the same domain/site collection. T ...