简体   繁体   中英

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.

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.

You don't need moment for that, since is deprecated.
Just do like that:

class_dates.sort((a,b) => new Date(a) - new Date(b))
// ['2023-01-05', '2023-01-07', '2023-02-04', '2023-02-11', '2023-02-18', '2023-02-25']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM