0

I have an array in javascript with three values per array object, a name, start and end time that i'm iniating as follows:

var list = [];

Later in my code, i enter data into this array as follows:

var pushString = "{\"naam\": \"" + naamzonderNummer + "\", \"starttime\": \"" + begintijd + "\", \"stoptijd\": \""  + eindtijd + "\"}";
              list.push(pushString);

This seems to work fine, as the log outputs my array like:

[{"naam": "Pete ", "starttime": "15:00", "stoptijd": "20:00"},
 {"naam": "John ", "starttime": "12:30", "stoptijd": "20:00 "},
 {"naam": "Doe ", "starttime": "08:00", "stoptijd": "11:30"}]

However, when i try to sort this array using the following code:

list.sort(function(a, b) {
  var keyA = new Date(a.starttime),
    keyB = new Date(b.starttime);
  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});

The output however, isn't sorted. I want this to sort from the earliest time(starttime) to the latest. My output stays the same.

What i am trying to achieve:

[{"naam": "Doe ", "starttime": "08:00", "stoptijd": "11:30"},
 {"naam": "John ", "starttime": "12:30", "stoptijd": "20:00 "},
 {"naam": "Pete ", "starttime": "15:00", "stoptijd": "20:00"}]

I have tried pretty much every solution and function i could find in regards to sorting this array without succes. Im guessing it's not the function that's wrong but something with the array. But i am out of ideas.

MGSneaky
  • 13
  • 4
  • 1
    The issue is here at `new Date(a.starttime)`. It is invalid format so the date becomes invalid dates and both ifs evaluate to `false` always. Read more about the formats [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date). Using proper date format will fix the issue here – Sunil Chaudhary Nov 13 '22 at 23:12
  • 1
    actually, you don't need a proper date format ... since times can be sorted as if they are strings (no, really, it's a fact, "08:00" < "12:30") - `data.sort(({starttime:a}, {starttime:b})=> a.localeCompare(b));` – Jaromanda X Nov 13 '22 at 23:14

0 Answers0