Search code examples
node.jsarrayssortingmomentjssails.js

How do i sort the dates in a array in ascending order in nodejs?


In my code i have an array how do i sort the array in the ascending order

"class_dates": [
  "2023-02-04",
  "2023-02-11",
  "2023-02-18",
  "2023-02-25",
  "2023-01-05",
  "2023-01-07"
]

How do i get them sorted in a ascending order like below

"class_dates": [
  "2023-01-05",
  "2023-01-07",
  "2023-02-04",
  "2023-02-11",
  "2023-02-18",
  "2023-02-25"
]

I am using moment & nodejs.


Solution

  • You could use a custom sort function on the Array:

    const moment = require('moment');
    var class_dates = [
          "2023-02-04",
          "2023-02-11",
          "2023-02-18",
          "2023-02-25",
          "2023-01-05",
          "2023-01-07"
        ];
    let sorted_dates = class_dates.sort((a, b) => {
        return moment(a).diff(b);
    });
    console.log(sorted_dates);
    

    Note that this is by no means optimal when you deal with a large array as you will be parsing every date with moment.js multiple times. It would be better to first convert all dates into moment-objects, then compare those and after that convert them back into strings. Compare this version:

    const moment = require('moment');
    var class_dates = [
          "2023-02-04",
          "2023-02-11",
          "2023-02-18",
          "2023-02-25",
          "2023-01-05",
          "2023-01-07"
        ];
    let sorted_dates = class_dates
    .map((d) => {
        return moment(d)
    })
    .sort((a, b) => {
        return a.diff(b);
    })
    .map((d) => {
        return d.format('YYYY-MM-DD');
    });
    console.log(sorted_dates);
    

    The code is a bit more involved, but when you are dealing with a lot of data this should be done. If you are only dealing with a small Array like in this example you can probably ignore the performance impact.

    Edit: Since this got marked as the accepted answer I want to also highlight what Victor Manduca added in his answer: You absolutely don't need moment.js to do this. You can compare dates in Vanilla JS.