1
  const info = [{
                    "userID" : "aaa",
                    "dob" : "2021-07-23 22:30:00.000Z" <--- String
                }, 
                {
                    "userID" : "aaa11",
                    "dob" : "2021-06-10 12:30:00.000Z" <--- String
                }, 
                {
                    "userID" : "aaa22",
                    "dob" : "2021-09-23 22:30:00.000Z" <--- String
                }]

I've been using sort to rearrange the list. However, I am quite stuck, sorting with the string.

info.sort((a, b) => a.dob - b.dob);

This works with the number but does not work with the string. I've been trying to look for the answer here, however, I could not figure it out how to sort with the ISO date string. How can I do this?

isherwood
  • 58,414
  • 16
  • 114
  • 157
chichi
  • 2,777
  • 6
  • 28
  • 53

1 Answers1

1

You can use Date as follows:

const info = [ { "userID" : "aaa", "dob" : "2021-07-23 22:30:00.000Z" }, { "userID" : "aaa11", "dob" : "2021-06-10 12:30:00.000Z" }, { "userID" : "aaa22", "dob" : "2021-09-23 22:30:00.000Z" } ];

const sorted = info.sort(({ dob: a }, { dob: b }) => new Date(a) - new Date(b));

console.log(sorted);

Another way using String#localeCompare:

const info = [ { "userID" : "aaa", "dob" : "2021-07-23 22:30:00.000Z" }, { "userID" : "aaa11", "dob" : "2021-06-10 12:30:00.000Z" }, { "userID" : "aaa22", "dob" : "2021-09-23 22:30:00.000Z" } ];

const sorted = info.sort(({ dob: a }, { dob: b }) => a.localeCompare(b));

console.log(sorted);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 1
    Pretty much the same as the accepted answer on the duplicate, especially after the edit, which came after I added the potential duplicate... – Heretic Monkey Jun 23 '21 at 20:41
  • I was applying it on `MongoDB` `$function`, that was why, `new Date()` did not work. However, this has worked as expected! Thank you so much mate. – chichi Jun 24 '21 at 03:08