Arranging numerous items based on date in JavaScript without prior knowledge

I'm facing an issue where I need to showcase JSON data containing events but want them sorted by time. The challenge is that the number of objects in the JSON can vary as users can keep adding more. Below is my code snippet demonstrating how the display should look like.

          {
            "events":[{
                        "start":     "2018-05-29T09:15:00+02:00",
                        "end":       "2018-05-29T10:00:00+02:00",
                        "summary":   "BreakfastOps",
                        "organizer": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf3eefbfdf2f5e6f9eeefdcf9f1fdf5f0b2eff5">[email protected]</a>",
                        "meet_url":  "https://meet.google.com/exampleLink"
                    }
           ]
        }

The events array could contain more objects, and I aim to sort them based on their start times for a well-organized display. Here's an image of unsorted events. Do note that there are additional event objects not shown here.

Update: Per request, I've included the code snippet from my main.js file.

$.getJSON(some kind of url., render)
function render(data){
    console.log(data.events.length)
 let filteredDate = data.events.filter((item) =>{
            let endTime = new Date(item.end);
            if(Date.now()<endTime){
              return item;
            }
     });

 let filteredDate2 = filteredDate.filter((item2)=>{
     let startTime = new Date(item2.start);
     if(Date.now()>startTime){
         return item2;
     }
 });   
 //and so on...

} 


   /* Displays current date*/ 
    var date = document.getElementById('date')
    var currentTime = new Date()
    var month = currentTime.getMonth() + 1
    var day = currentTime.getDate()
    var year = currentTime.getFullYear()
    var hours = currentTime.getHours()  
    var minutes = currentTime.getMinutes()
         if (minutes < 10){
            minutes = "0" + minutes
        }
    date.innerHTML = (hours + ':'+minutes+" "+ month + "/" + day + "/" + year)

Answer №1

In order to sort date values in your JSON, which are represented as strings, you will need to convert them using the new Date() method. This will allow you to get the total time value that can be used to properly sort the objects within the array. Here is an example:

var data = {
    "events":[
    {
      "start":     "2018-05-29T09:15:00+02:00",
      "end":       "2018-05-29T10:00:00+02:00",
      "summary":   "BreakfastOps",
      "organizer": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f9e4f1f7f8ffecf3e4e5a7d6f3fbf7fffab8e5ff">[email protected]</a>",
      "meet_url":  "https://meet.google.com/exampleLink"
    },
    {
      "start":     "2018-04-29T09:15:00+02:00",
      "end":       "2018-05-29T10:00:00+02:00",
      "summary":   "BreakfastOps",
      "organizer": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e9f4e1e7e8effce3f4f5b4c6e3ebe7efeaa8f5ef">[email protected]</a>",
      "meet_url":  "https://meet.google.com/exampleLink"
    },
    {
      "start":     "2018-03-29T09:15:00+02:00",
      "end":       "2018-05-29T10:00:00+02:00",
      "summary":   "BreakfastOps",
      "organizer": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e011c090f0007140b1c1d5d2e0b030f0702401d07">[email protected]</a>",
      "meet_url":  "https://meet.google.com/exampleLink"
    }
   ]
};
data.events.sort(function(a, b){
   return new Date(a.start).getTime() - new Date(b.start).getTime()
});
console.log(data);

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

Decoding multidimensional arrays in JSON using PHP

I am extracting information from the following website: "" and converting it into JSON format using a PHP script. The JSON output appears as follows: ( [Term-array-array] => Array ( [Term-array] => Array ( [Term] => Array ( [0] => loves [1] = ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...

Serialize a form while keeping the submitted data private

Is there a way to achieve serialization without triggering the submit function for an ajax call? I've searched extensively for a solution to this issue without any luck. The java script function is invoked when a button within the form is clicked. do ...

What is the best way to import a YAML file into a Vue project?

As a newcomer to Vue and the world of web development, I recently embarked on building a small app. In order to store data with comments, I opted to use YAML instead of JSON. I experimented with two different YAML parsers: https://github.com/nodeca/js-ya ...

Interactive selection menu with jquery technology

I am in the process of developing a dynamic dropdown feature using jQuery var rooms = $("<select />"); $(res.data).each(function () { var option = $("<option />"); option.html(this.name); op ...

What is the proper way to correctly invoke NuxtServerInit?

Code snippet from the VUEX repository: export const state = () => ({ z: 'sdfjkhskldjfhjskjdhfksjdhf', }); export const mutations = { init_data_for_firmenistorie2 (state, uploadDbFirmenistorieData){ state.z = uploadDbFirmenistorieD ...

Accessing information from JSON files using AJAX

I'm currently working on loading data from a JSON file using AJAX. The file I'm referencing is external-file.json. Within the code snippet provided, there are other unrelated sections. I'm encountering an issue within the getViaAjax function ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

What is the best way to divide my HTML page in half?

My goal is to display two maps side by side, one on the right and the other on the left. However, when I try to implement this, one map appears on top of the other. I believe that CSS positioning can help me achieve the desired layout, but as a beginner in ...

How to use Laravel to show a graph sourced from a separate database connection

Is it possible to create a pie or doughnut chart in Laravel using data from a separate database connection ('mysql2' in the .env file)? I have successfully generated charts from the main database, but this time I didn't migrate the second da ...

Firefox is giving me trouble with my CSS/JS code, but Chrome seems to be working

Having some trouble with this code - it seems to be working fine in most browsers, but Firefox is giving me a headache. I've tried using the moz abbreviations in CSS and JS tweaks, but no luck. Is there a property that Mozilla Firefox doesn't sup ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Two Elements Linked Together

I'm facing an issue with my interconnected React components. Despite being separate entities, they appear to share some styling attributes which I find puzzling. The main problem lies in the footer component as it seems linked to another component, p ...

Invoking numerous functions through the (click)= event

When it comes to removing a user from my site, I find myself having to execute multiple database queries to delete the user's ID across approximately 10 different tables. Currently, I am resorting to what I consider a messy workaround where I have mu ...

Can you identify the issue in this code?

I am facing an issue with using this code to save values in a table when the page loads. The function that searches for values is written in PHP, and I need to use these values in my script. Unfortunately, the current approach I am trying doesn’t seem ...

I am experiencing excessive paper skipping in my printer

I have been using the 80 column dot matrix printer. However, after each printout, the paper skips two times resulting in a lot of wasted paper. How can I resolve this issue? Currently, I am only utilizing the window.print() JavaScript function. Are there ...

Guide to transposing a matrix using ARM assembly instructions

I need to transpose 8 arrays of n-bits each, with around 70,000 bits, into a byte array with n elements. The context is that these arrays represent RGB data for 8 channels, and I require one byte to represent the nth-bit position of each of the 8 arrays. T ...

Functional Components with Methods in ReactJS

When creating a functional stateless component that requires methods to access props, is there a recommended approach or best practice to follow? For instance: function Stateless(props) { function doSomething(props) { console.log(props); } ...