skip to content
Alvin Lucillo

Date sort in ts/js

/ 1 min read

Sorting in ts/js is straightforward to. You just need to pass a comparator function. The value of the function determines the sorting order. If 0, no order change. If negative, then a comes before b. If positive, a comes after b. In our example, the original dates are ordered in ascending order. After the sort, they are now in descending order. How so? Using getTime() we get the full timestamp of two dates being compared. Subtracting the timestamps, 2025-05-23 as a and 2025-05-24 as b, results in a positive value. Thus, their positions are swapped.

const dt1 = new Date();
const dt2 = new Date();
dt2.setDate(dt2.getDate() + 1);
const dt3 = new Date();
dt3.setDate(dt3.getDate() + 2);
const dates: Date[] = [dt1, dt2, dt3];

console.log(dates); // [Date: "2025-05-22T13:13:38.144Z", Date: "2025-05-23T13:13:38.144Z", Date: "2025-05-24T13:13:38.144Z"]

dates.sort((a: Date, b: Date) => b.getTime() - a.getTime());
console.log(dates); // [Date: "2025-05-24T13:13:38.144Z", Date: "2025-05-23T13:13:38.144Z", Date: "2025-05-22T13:13:38.144Z"]