To sort by date in JavaScript, pass a compare function to Array.prototype.sort() and compare timestamps. Without a compare function, sort() converts values to strings, which is not reliable for date ordering.
The common pattern is array.sort((a, b) => new Date(a.date) - new Date(b.date)) for ascending order and the reverse subtraction for descending order.
Tested On: The examples were tested with Node.js v20.18.1 on a Linux system. The same Date and array sorting behavior works in modern browsers and JavaScript runtimes.
Method 1: Sort Objects by Date Ascending
const posts = [
{ title: "old", date: "2023-01-10" },
{ title: "new", date: "2024-02-05" },
{ title: "mid", date: "2023-06-15" },
];
posts.sort((a, b) => new Date(a.date) - new Date(b.date));
console.log("sort-asc:", posts.map((post) => post.title).join(">"));Tested output:
sort-asc: old>mid>newAscending order puts the oldest date first.
Method 2: Sort Objects by Date Descending
posts.sort((a, b) => new Date(b.date) - new Date(a.date));
console.log("sort-desc:", posts.map((post) => post.title).join(">"));Tested output:
sort-desc: new>mid>oldDescending order puts the newest date first.
Method 3: Sort Date Objects Directly
const dates = [new Date("2024-02-05"), new Date("2023-01-10")];
dates.sort((a, b) => a - b);Date objects convert to timestamps during subtraction.
Method 4: Avoid Mutating the Original Array
sort() mutates the original array. Copy first when the original order must remain available.
const sorted = [...posts].sort((a, b) => new Date(a.date) - new Date(b.date));Modern runtimes also support toSorted() for non-mutating sorting.
Common Questions About Sorting Dates in JavaScript
Does JavaScript sort mutate the array?
Yes. sort() sorts the array in place and returns the same array reference.
Should I sort dates as strings or Date objects?
ISO date strings such as YYYY-MM-DD sort lexicographically, but converting to Date or timestamps is clearer when working with mixed date-time values.
How do I sort newest first?
Use new Date(b.date) - new Date(a.date).
Summary
To sort dates in JavaScript, use Array.sort() with a compare function that subtracts timestamps. Use ascending subtraction for oldest first and reverse subtraction for newest first. Remember that sort() mutates the original array, so copy the array first when you need a non-mutating sort.
