Quickest method for arranging a multi-dimensional array with dates in sequential order

I have a list of appointments with dates and times as shown below:

[
    ["John Doe", "10 Sep. 2017 2:00 PM"],
    ["Jane Smith", "10 Sep. 2017 2:00 PM"],
    ["Alice Johnson", "10 Sep. 2017 1:00 PM"],
    ["Bob Williams", "10 Sep. 2017 8:00 AM"],
    ["Mark Davis", "9 Sep. 2017 2:00 PM"],
    ["Emily Brown", "9 Sep. 2017 2:00 PM"],
    ["David Lee", "9 Sep. 2017 1:00 PM"],
    ["Sarah Parker", "9 Sep. 2017 8:00 AM"]
]

My goal is to rearrange the appointments so that the dates are in ascending order, but the times are reversed chronologically. The desired output is:

[
    ["John Doe", "10 Sep. 2017 8:00 AM"],
    ["Alice Johnson", "10 Sep. 2017 1:00 PM"],
    ["John Doe", "10 Sep. 2017 2:00 PM"],
    ["Jane Smith", "10 Sep. 2017 2:00 PM"],
    ["Bob Williams", "9 Sep. 2017 8:00 AM"],
    ["David Lee", "9 Sep. 2017 1:00 PM"],
    ["Mark Davis", "9 Sep. 2017 2:00 PM"],
    ["Emily Brown", "9 Sep. 2017 2:00 PM"]
]

I currently have a sorting function implemented which sorts the appointments based on date. How can I modify this existing code to sort the appointments by time within each date?

function sortTable(data) {

  return sortTableHelper(data);

  function sortTableHelper(data) {
   data = data.sort((elem1, elem2) => {
     var date1 = moment(elem1[1], 'D MMM YYYY h:m A')
       , date2 = moment(elem2[1], 'D MMM YYYY h:m A');

     if (date1.isAfter(date2)) return 1;

     return -1;
   });

   return data;
 }
}

Answer №1

If you want to achieve your desired result, you need to sort by date excluding the hours and then by the hours separately. Here is how you can do it:

var input = [["First Name", "10 Sep. 2017 2:00 PM"], ["First Name", "10 Sep. 2017 2:00 PM"], ["First Name", "10 Sep. 2017 1:00 PM"], ["First Name", "10 Sep. 2017 8:00 AM"], ["First Name", "9 Sep. 2017 2:00 PM"], ["First Name", "9 Sep. 2017 2:00 PM"], ["First Name", "9 Sep. 2017 1:00 PM"], ["First Name", "9 Sep. 2017 8:00 AM"]];

function sortTable(data) {

  return sortTableHelper(data);

  function sortTableHelper(data) {

   return data.sort((a, b) => {
     var dateA = new Date(a[1]);
     var dateB = new Date(b[1]);
 
     return dateA.getHours() - dateB.getHours() + dateB.setHours(0) - dateA.setHours(0);
   });
 }
}

console.log(sortTable(input));

Note: This is achieved without using momentjs.

Answer №2

To change the order of your results from descending to ascending, invert the return code:

if (date1.isAfter(date2)) return 1;
if (date2.isAfter(date1)) return -1;
return 0;

I modified the code to return 0 when the items are equal.

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

Displaying AngularJS content as text in an HTML file

I have been learning from the AngularJS Tutorial on Code School, but I'm experiencing an issue where my JavaScript code is not rendering properly in the HTML. Below is the snippet of HTML code: <html ng-controller="StoreController as store"> & ...

Different methods for dynamically altering the style attribute

Here's some code I wrote: <html> <head> <style> .containerTitle { background-color:silver; text-align:center; font-family:'Segoe UI'; font-size:18px; font-weight:bold; height:30px; } ...

Is it possible to conceal an HTML form once it has been submitted

I have a form on my website that sends the entered information to a PHP script which then emails me the details. I've implemented JavaScript form validation and jQuery Ajax to ensure the page doesn't need to be reloaded. Here is the HTML code fo ...

Each time the website refreshes, Object.entries() rearranges the orders

After reading the discussion on Does JavaScript guarantee object property order? It seems that Object.entries() should maintain order. However, I encountered an issue with my Angular website where the order of keys in Object.entries() changed upon refres ...

The issue with using useState on arrays is that it is not functioning properly with React Hooks

const [LatestNews, setLatestNews] = useState([]); useEffect(() => { async function fetchLatestData() { const result = await database.collection('latestnews').get(); result.docs.forEach(doc => ...

Attempting to enable a checkbox using a controller located in a separate controller

I am attempting to trigger a checkbox from a separate controller. Suppose I have a card called information technology under one controller, and when clicked, it should redirect to another page that contains a checkbox for information technology managed by ...

The issue with angular JavaScript in the child component is causing the left side navigation dropdown to malfunction

I'm currently facing an issue with the left side navigation in my home component. The dropdown functionality is not working within one of the routing modules (admin-routing.module.ts). Interestingly, the navigation works perfectly fine in app-routing. ...

Is there a way to incorporate CSS or tables when converting HTML to PDF using JavaScript?

While working on a project, I successfully converted an HTML file into a PDF. However, the output did not display the CSS design. Can anyone provide suggestions on how to include CSS design in the PDF file? Below is the JavaScript function code: $(funct ...

Is there a way to deactivate or dim a specific hour in an HTML time form?

I am currently facing a challenge with my booking form. I need to find a way to grey-out or disable the hours/times that have already been booked by previous customers. This will help ensure that the next person can select a different time slot. However, I ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

CAUTION: Attempted to initialize angular multiple times...all because of jQuery...such a puzzling issue, isn

I am attempting to comprehend the situation at hand. The warning is clear, and I acknowledge that in my application, with the provided code and structure, the ng-view runs twice ('test' is logged twice in the console, indicating that angular is l ...

Unable to change background-image as intended

Here is an example of my HTML code with an initial background image: <div id="ffff" style="width: 200px; height: 200px; background-image: url('/uploads/backroundDefault.jpg')">sddsadsdsa<br>dffdsdfs</div> Everything seems to b ...

The expiration period set in expireAfterSeconds doesn't seem to be functioning as expected in the time-to-live (ttl) configuration. Rows are

Can you please take a look at my code and provide some feedback? The issue I am facing is that the record is getting deleted without specifying the number of seconds. I have tried changing from createIndex to ensureIndex but it's still not working as ...

Including extra js files disrupts the jQuery IntelliSense functionality

After enjoying the benefits of jQuery IntelliSense in VS2008, I decided to add a reference to jQuery UI. However, upon doing so, I noticed that the jQuery IntelliSense disappeared. It seems that referencing another .js file in the document causes this is ...

Combining two elements in Angular 2

I am looking to find the intersection of two objects. My goal is to compare these objects and if they have matching values on corresponding keys, then I want to add them to a new object. obj1 = { "Projects": [ "test" ], "Companies": [ "facebook", "google ...

Express router parameter matching

Let's consider a scenario where I have two routes - one with parameters and one without: /foo?bar /foo I aim to assign different handlers for these routes. Instead of the conventional approach, I am looking for a way to simplify the code. app.use(&a ...

Encountering the error "Cannot access property 'stroke' of undefined" when utilizing constructors in React and p5

Hi there, I'm having trouble with my React code and could really use some assistance. Being new to React, I'm trying to create a collision system between multiple bubbles in an array, but I keep running into this undefined error: import React, ...

Can Jquery use .hover to add a class or Child:hover to impact its parent element?

I have been searching for a solution tailored to my specific needs, and I am encountering difficulties in getting a seemingly simple jQuery code to function as expected. Here is the link to my basic fiddle: http://jsfiddle.net/LBHxc/ (I apologize for the ...

When using Ajax in Jquery and expecting data of type JSON, the response always seems

Looking to create a basic jQuery Ajax script that checks a user's discount code when the "Check Discount Code" button is clicked? Check out this prototype: <script> jQuery(function($) { $("#btn-check-discount").click(function() { c ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...