skip to Main Content

I am creating an array of objects, which looks like

let obj = {
    date: String,
    time: String,
    text: String,
  }

The date format is "MM-DD-YYYY" and format of time "HH:MM:SS"
I am getting this from an API and can’t change the format, I need to sort the array in increasing order of date and time, that is for the same date, increasing order of time. I have tried using JS Date and Moment, but was not able to do it.
Sorting only by date works using Date(a.date) - Date(b.date), but if I try to include the time as well, it does not, not even
(Date(a.date) - Date(b.date)) || (a.time.localeCompare(b.time))

How can I do this in JavaScript (NodeJS)?

3

Answers


  1. Chosen as BEST ANSWER

    I was able to solve this by the following sort function:

    arr.sort((a, b) => {
      // Convert date strings to Date objects
      const dateA = new Date(a.date);
      const dateB = new Date(b.date);
    
      // Compare dates
      if (dateA < dateB) return -1;
      if (dateA > dateB) return 1;
    
      // If dates are equal, compare times
      const timeA = a.time.split(':');
      const timeB = b.time.split(':');
    
      for (let i = 0; i < 3; i++) {
        const numberA = parseInt(timeA[i]);
        const numberB = parseInt(timeB[i]);
    
        if (numberA < numberB) return -1;
        if (numberA > numberB) return 1;
      }
    
      return 0;
    });
    

    Cheers to ChatGPT!


  2. You can convert the date and time strings to JavaScript Date objects and then use the sort() method:

    arr.sort(function(a, b) {
      // Convert date strings to Date objects
      let dateA = new Date(a.date + " " + a.time);
      let dateB = new Date(b.date + " " + b.time);
    
      // Compare dates and times
      if (dateA < dateB) {
        return -1;
      } else if (dateA > dateB) {
        return 1;
      } else {
        return 0;
      }
    });
    
    Login or Signup to reply.
  3. With the following sorting logic, you can has the date and time together so that you do not need to re-parse each item every time it is compared to another.

    const main = () => {
      const sortedData = data.sort((a, b) =>
          retrieveByDateAndTime(a) - retrieveByDateAndTime(b)
        || a.text.localeCompare(b.text));
    
      hashLookup.clear(); // Clear the map (optional)
    
      console.log(sortedData); // Display the sorted data
    }
    
    // Optimize sorting speed by hashing
    const hashLookup = new Map();
    const parseDateAndTime = (date, time) => {
      const [_month, _date, _year] = date.split('-').map(v => parseInt(v, 10));
      const [_hour, _min, _sec] = time.split(':').map(v => parseInt(v, 10));
      return new Date(_year, _month - 1, _date, _hour, _min, _sec);
    };
    const retrieveByDateAndTime = ({ date, time }) => {
      const hash = generateHashCode(date + 'T' + time);
      let storedDate = hashLookup.get(hash);
      if (!storedDate) {
        storedDate = parseDateAndTime(date, time);
        hashLookup.set(hash, storedDate);
      }
      return storedDate;
    };
    
    // Credit: https://stackoverflow.com/a/8831937/1762224
    const generateHashCode = (str) => {
      let hash = 0;
      for (let i = 0, len = str.length; i < len; i++) {
        let chr = str.charCodeAt(i);
        hash = (hash << 5) - hash + chr;
        hash |= 0;
      }
      return hash;
    }
    
    // Generated with https://www.mockaroo.com
    const data = [
      { "date": "06-29-2022", "time": "14:27:00", "text": "Mustang"     },
      { "date": "11-10-2022", "time": "20:42:00", "text": "Firebird"    },
      { "date": "06-29-2022", "time": "00:22:00", "text": "Mustang"     },
      { "date": "11-10-2022", "time": "20:00:00", "text": "E-Series"    },
      { "date": "06-29-2022", "time": "10:58:00", "text": "E-Series"    },
      { "date": "05-18-2022", "time": "02:59:00", "text": "IS"          },
      { "date": "01-14-2023", "time": "09:15:00", "text": "Truck"       },
      { "date": "01-13-2023", "time": "00:17:00", "text": "CLS-Class"   },
      { "date": "11-10-2022", "time": "18:10:00", "text": "Oasis"       },
      { "date": "09-14-2022", "time": "04:15:00", "text": "Monte Carlo" }
    ];
    
    main(); // Now, call main
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search