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!