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

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

Having trouble connecting to JSTL in my JavaScript file

Currently, I am facing an issue with my JSTL code that is housed within a JavaScript file being included in my JSP page. The problem arises when I place the JSTL code inside a script within the JSP page - it works perfectly fine. However, if I move the s ...

Progress Bar Countdown Timer

I have made some progress on my project so far: http://jsfiddle.net/BgEtE/ My goal is to achieve a design similar to this: I am in need of a progress bar like the one displayed on that site, as well as the ability to show the days remaining. Additionally ...

Tips for extracting the image URL from my JSON string

I am in possession of a json file that includes URLs for images, and I have come across something that seems to be a URL, which is encoded as: iVBORw0KGgoAAAANSUhEUgAAADYAAAAzCAMAAADrVgtcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6m ...

Choose up to three elements using jQuery

DEMO I'm currently working on a project where I need to select only 3 items at a time. However, all the elements are being selected instead. Can someone please provide guidance on how to achieve this? "If a user wants to select another element, th ...

Ways to showcase a JSON menu with a single level

I have a json file containing links to all the images in a specific folder, as shown below: ["http://img1.png","http://img2.png","http://img3.png","http://img4.png"] I would like to create a <ul> list using this data, but I'm not sure how to d ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Removing duplicate entries from a dropdown menu can be achieved by implementing

As a newcomer to the world of PHP PDO, I've learned that the database connection should be in a separate PHP file. However, after spending an entire day trying different things, I'm still facing issues. I suspect that the duplicate entries are a ...

When you click on a sublevel in the vertical CSS and JavaScript onclick menu, it disappears automatically

I'm a beginner when it comes to Javascript, and I'm still getting the hang of CSS/HTML. Currently, I am working on creating a vertical menu using CSS and javascript. My goal is to have the sublevels appear on the right side of the menu when someo ...

Is there a way to create a Vue component that can process dynamic formulas similar to those used in

I am looking to create a component that has the ability to accept different formulas for computing the last column. The component should use these formulas in Vuex getters to store the total state values passed to it. Here are the specifications for the c ...

Obtain the filepath of the uploaded file

After working on a code to allow users to upload images to the server, I encountered an issue. Here is my setup: The backend of my system is built using Node JS. My main goal is to retrieve the file path of the uploaded image so that I can successfully up ...

Modifying the content in one form field based on the information entered in another input field

I have a scheduling application that includes a form for selecting both the departure city and arrival city. The app is designed for international travel only, so when a user selects a city from Hungary as the departure city, I want to exclude all Hungaria ...

Interactive button visual effect

I have a piece of code that currently plays audio when I click on an image. However, I am looking to modify it so that not only does clicking on the image play the audio, but it also changes the image to another one. Can anyone assist me with this? Here i ...

Hide the button with jQuery Ajax if the variable is deemed acceptable upon submission

I need to figure out how to hide the submit button if the email entered is the same as the one in the database from action.php. Can anyone help me with integrating this functionality into my existing code? <form onsubmit="return submitdata();"> ...

"Enhancing user experience with React.js and Socket.io: dynamically updating list item positions based on

export default class ReactApp extends React.Component { constructor(props) { super(props) this.state = { status: [], services: [] } fetchData((err,opt, data) => { function Exists(l ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Forge: Securely encrypting massive files

I rely on the forge framework for implementing PGP functionality, specifically for encrypting large files (2gb or larger) while minimizing RAM usage. What would be the most efficient approach to achieve this? ...

The default value of the select option will not be displayed upon loading and will also not appear when another option is selected

I created a form using vue.js that includes a select option dropdown. However, the default value does not display when the form loads, and when a new option is selected from the dropdown, it also does not show. When I use v-for to loop through all options ...

Searching DynamoDB in node.js using mapped items

In my DynamoDB table, I am trying to retrieve all Items where the Review.ID matches 123. Item: { id: 1, review: { Id: 123, step1: 456, step2: 789, step3: 1234, }, // Add more items here }, Item: { id: 2, review: { Id: 123 ...