-2

I have a javascript array of timestamps as strings like this:

["6/10/2020 @ 10:1", "6/10/2020 @ 9:37", "6/10/2020 @ 12:1", "6/10/2020 @ 9:42", "6/10/2020 @ 12:2", "6/10/2020 @ 11:19", "6/10/2020 @ 10:50", "6/10/2020 @ 9:35", "6/10/2020 @ 9:36", "6/10/2020 @ 12:0"]

I tried to sort them, but neither the regular sort or the reverse sort worked correctly. How could I do it?

Liiuc
  • 162
  • 1
  • 13
  • 1
    Parse them as actual `Date` objects, then sort by value, or use string manipulation to format them in a sortable format (e.g., yyyy-mm-dd HH:mm). – Heretic Monkey Oct 06 '20 at 15:10

1 Answers1

1

If you really need to keep the format you posted, you'd need to change and change it back.. you could do something like this:

  let strings = ["6/10/2020 @ 10:1", "6/10/2020 @ 9:37", "6/10/2020 @ 12:1", "6/10/2020 @ 9:42", "6/10/2020 @ 12:2", "6/10/2020 @ 11:19", "6/10/2020 @ 10:50", "6/10/2020 @ 9:35", "6/10/2020 @ 9:36", "6/10/2020 @ 12:0"];
  let dates = strings.map(x=> {
    let parts = x.split(" ");
    let dateParts = parts[0].split("/");
    let timeParts = parts[2].split(":");
    return { date: new Date(dateParts[2],dateParts[1],dateParts[0],timeParts[0],timeParts[1]), string: x };
  });
  dates.sort( (x,y)=> x.date - y.date);
  strings = dates.map(x=> x.string);

(this keeps the original format, and lets you build the date however you expect the format to be, you should add checks to make sure the date strings are valid)

which returns:

["3/5/2020 @ 9:35","3/5/2020 @ 9:36","3/5/2020 @ 9:37","3/5/2020 @ 9:42","3/5/2020 @ 10:1","3/5/2020 @ 10:50","3/5/2020 @ 11:19","3/5/2020 @ 12:0","3/5/2020 @ 12:1","3/5/2020 @ 12:2"]
audzzy
  • 721
  • 1
  • 4
  • 12
  • 1
    You should be very careful when use `Date(string)` to parse dates. See [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552) – Heretic Monkey Oct 06 '20 at 15:25