Code snippet: Retrieve the previous and upcoming events based on the current date from an array (JavaScript/Angular)

Is there anyone who can assist me with an algorithm? I have a list of events and need to retrieve the next event and previous events based on the current date.

For example:

I fetch all events from an SQL database like so:

events = [
    {eventId:1, eventDate: "Wen Apr 01 2015 18:41:00 GMT+0300", eventPlace:"Dortmund, DE"},
    {eventId:2, eventDate: "Sun Apr 05 2015 23:41:00 GMT+0300", eventPlace:"Budapest, HU"},
    {eventId:3, eventDate: "Fri Apr 03 2015 13:41:00 GMT+0300", eventPlace:"Madrid, ES"},
    {eventId:4, eventDate: "Mon Jun 01 2015 22:00:00 GMT+0300", eventPlace:"London, EN"},
    .......
    {eventId:100, eventDate: "Mon Aug 31 2015 22:00:00 GMT+0300"}
    ]

If the current date is Sun Apr 05 2015 15:00:00, I would like to obtain:

resultNextEv= {eventId:2, eventDate: "Sun Apr 05 2015 23:41:00 GMT+0300", eventPlace:"Budapest, HU"}
resultLastEv= {eventId:3, eventDate: "Fri Apr 03 2015 13:41:00 GMT+0300", eventPlace:"Madrid, ES"}
    

What is the most efficient way to achieve this result? (I am using JavaScript / Angular) Any suggestions or ideas?

Thank you

Answer №1

Start by arranging the events in chronological order:

var sortedEvents = events.sort(function(a, b) {
  return new Date(a.eventDate) - new Date(b.eventDate);
});

Next, go through the sorted events list. If a date is before the target date, mark it as the previous event. If it's after the target date, mark it as the next event and stop iterating:

function getDates() {
  var sortedEvents = events.sort(function(a, b) {
    return new Date(a.eventDate) - new Date(b.eventDate);
  });
  var currentDate = new Date(document.getElementById('date').value),
      index, selectedDate;

  for (index = 0; index < sortedEvents.length; index++) {
    selectedDate = new Date(sortedEvents[index].eventDate);
    if (selectedDate > currentDate) break;
  }

  // Perform actions using sortedEvents[index-1] and sortedEvents[index]
} //getDates

To retrieve the last N events, refer to sortedEvents[index-1], sortedEvents[index-2], and so on up to sortedEvents[index-N].

To fetch the next N events, utilize sortedEvents[index], sortedEvents[index+1], and continue until sortedEvents[index+N-1].

Fiddle

Answer №2

let activities = [
    {activityId:1, activityDate: "Wen Apr 01 2015 18:41:00 GMT+0300", location:"Dortmund, DE"},
    {activityId:2, activityDate: "Sun Apr 05 2015 23:41:00 GMT+0300", location:"Budapest, HU"},
    {activityId:3, activityDate: "Fri Apr 03 2015 13:41:00 GMT+0300", location:"Madrid, ES"},
    {activityId:4, activityDate: "Mon Jun 01 2015 22:00:00 GMT+0300", location:"London, EN"}
    ];

 // organize the activities 
 let sortedActivities = activities.sort(function(a, b) {
  return new Date(a.activityDate) - new Date(b.activityDate);
  });

let currentTime = new Date("Sun Apr 05 2015 15:00:00");
let upcomingActivities = [];
let pastActivities = [];

// finding the next activity after the current time
for(let i = 0; i < sortedActivities.length; i++){
  if(new Date(sortedActivities[i].activityDate) > currentTime) {
    upcomingActivities.push(sortedActivities[i]);
    }
}

// finding the previous activity before the current time
for(let i = sortedActivities.length - 1; i >= 0; i--){
  if(new Date(sortedActivities[i].activityDate) < currentTime) {
    pastActivities.push(sortedActivities[i]);
    }
}

console.log("Current Time: " + currentTime);
console.log("Next Activity: " + upcomingActivities.length ? upcomingActivities[0].activityDate : undefined);
console.log("Previous Activity: " + pastActivities.length ? pastActivities[0].activityDate : undefined);

Codepen: http://codepen.io/andrerpena/pen/WbBwbG

If you need multiple future or past activities, simply loop through upcomingActivities or pastActivities. For instance, the next two activities are upcomingActivities[0] and upcomingActivities[1]

Answer №3

If you ever wondered how to achieve this effortlessly, look no further than the open source project jinqJs

var events = [
    {eventId:1, eventDate: "Wen Apr 01 2015 18:41:00 GMT+0300", eventPlace:'Dortmund, DE'},
    {eventId:2, eventDate: "Sun Apr 05 2015 23:41:00 GMT+0300", eventPlace:'Budapest, HU'},
    {eventId:3, eventDate: "Fri Apr 03 2015 13:41:00 GMT+0300", eventPlace:'Madrid, ES'},
    {eventId:4, eventDate: "Mon Jun 01 2015 22:00:00 GMT+0300", eventPlace:'London, EN'},
    {eventId:100, eventDate: "Mon Aug 31 2015 22:00:00 GMT+0300", eventPlace:'London, EN'}
    ]
;


var result1 = jinqJs().from(events).orderBy('eventDate').where(function(row){return Date.parse(row.eventDate) < Date.parse('Sun Apr 05 2015 15:00:00');}).top(1).select();

var result2 = jinqJs().from(events).orderBy('eventDate').where(function(row){return Date.parse(row.eventDate) > Date.parse('Sun Apr 05 2015 15:00:00');}).bottom(1).select();

var result = jinqJs().from(result1,result2).select();

document.body.innerHTML += '<pre>' + JSON.stringify(result, null, 2) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

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

Having trouble getting JQuery Ajax POST to work in Codeigniter

Encountering an issue with jQuery AJAX post in CodeIgniter, where clicking the submit button triggers an error. Below is the code snippet: home.js form.on('submit', function(e){ e.preventDefault(); var fields = {}; form.find(' ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

With Ionic, you can use one single codebase for both iPad and iPhone

I currently have a complete app developed using ionic and angularjs that is functioning well on iPads and Android devices. Now we are looking to launch it for iPhones and Android smartphones with some design modifications. Is there a method to achieve th ...

Modify the appearance of a nested div using CSS hover on the main JSX container

Within the material-ui table component, I am dynamically mapping rows and columns. The className is set to clickableRow. The TableRow also includes a hover options div on the right side: const generateTableHoverOptions = () => { if (selected) { ...

Currently exploring AngularJS and looking to create a categorized list

Currently delving into the world of AngularJS, I am embarking on creating a web application. One of my current tasks involves creating a grouped list. I am utilizing a JSON file that contains various entries like: {"title":"videoTitle", "chapter":"2", "s ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Having difficulty transferring data from a JSON file on a different domain to a variable using Ajax

As a beginner in Ajax, I am currently exploring the use of Ajax Cross domain functionality to fetch data. The Ajax function is triggered from test.php, which then calls stats.php to request the desired data. The content of Stats.php: <?php $data = ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

Add a unique CSS style to both text and image using anchor tags

Why isn't the hover effect of color transition and underline being applied to the image? It seems to only work for text. While I understand that the color transition may require a change in image color, shouldn't the underline still occur? This ...

Exploring Bootstrap4: Interactive Checkboxes and Labels

My form design relies on Bootstrap, featuring a checkbox and an associated label. I aim to change the checkbox value by clicking on it and allow the label text to be edited by clicking on the label. The issue I'm facing is that both elements trigger t ...

Upon loading the page, I encountered an issue with the 'errors' variable in my ejs template, resulting in an 'undefined' error

When I load my page, I encounter an 'undefined' error with my 'errors' variable in the ejs template. The ejs template I have is for a contact form and it includes code to display errors as flash messages on the page if the form is inco ...

Querying a Database to Toggle a Boolean Value with Jquery, Ajax, and Laravel 5.4

I am facing an issue with a button I created to approve a row in a table. It seems that everything is working fine when clicking the button, but there is no change happening in the MySQL database Boolean column. Here is the code for my button: <td> ...

The issue arises when React child props fail to update after a change in the parent state

Here's the main issue I'm encountering: I am opening a websocket and need to read a sessionId from the first incoming message in order to use it for subsequent messages. This should only happen once. I have a child component called "processMess ...

Extract information from one webpage, proceed to the following page, and repeat the process, utilizing JavaScript on the site

Exploring various web scraping techniques, I've hit a roadblock and could use some assistance. Currently, my Python code successfully extracts data from the first page of my website. response = requests.get(url) soup = BeautifulSoup(r.text, 'ht ...

Is it possible to disable the timeout for a single call using Axios?

I have set up an axios client instance in my application like this: const backendClient = axios.create({ baseURL: window['getConfig']?.url?.backend, httpsAgent: new https.Agent({ rejectUnauthorized: false }), timeout: window['getConfig ...

Strip excess white space from a complex string using Javascript

I have the following sets of strings: 14/04/22 10:45:20 12.08N 87.65W 15.0 2.9ML Frente a Corinto 14/04/21 11:05:34 12.10N 87.70W 140.0 3.5MC Cerca de Masachapa 14/04/22 09:00:09 12.35N 86.44W 12.4 1.3ML Cerca del volcan Momotombo 14/04/21 23:33:37 1 ...

What is the best way to combine JavaScript objects with identical values?

We have a task to compare each input key with others to find any common values. If there are common values, we need to concatenate them together and display the pairs. If no common values are found, then an empty array should be displayed as output. inpu ...

Ways to deselect checkboxes with Typescript and Jquery

I have a set of checkboxes all labeled with the same 'types' class. There is a button on my webpage that should be able to toggle between selecting and deselecting all the checkboxes in this group. When checking the boxes, I use the following sc ...

What is the best way to eliminate a count from an array when a button is deselected using JavaScript?

Whenever a button is selected, the value appears on the console.log as expected when using an array. To enhance this functionality, I also need to find a way to remove the value from the console when the button is deselected. var totalWishlist = []; $( ...

The persistentFilter in the Tabulator is failing to verify for the headerFilterEmptyCheck

Using Tabulator version 4.4.3 When filtering the checkbox in the usual way, everything works fine. If I set a filtered checkbox to true on a column, it functions correctly: headerFilterEmptyCheck: function (value) { return !value; }, Howev ...