Sorting by date is a common task when working with arrays in JavaScript. Whether you’re organizing blog posts, user logs, or events, knowing how to sort arrays by date will keep your data clean and correctly ordered.
If you have an array of ISO date strings, you can sort them like this:
const dates = [
"2024-04-10",
"2023-12-01",
"2025-01-15"
];
dates.sort((a, b) => new Date(a) - new Date(b));
console.log(dates);
// Output: ["2023-12-01", "2024-04-10", "2025-01-15"]
When you’re dealing with objects (e.g. blog posts or events), you’ll usually sort by a property:
const posts = [
{ title: "Post 1", publishedAt: "2024-02-20" },
{ title: "Post 2", publishedAt: "2023-11-05" },
{ title: "Post 3", publishedAt: "2024-09-01" }
];
posts.sort((a, b) => new Date(a.publishedAt) - new Date(b.publishedAt));
console.log(posts);
/* Output:
[
{ title: "Post 2", publishedAt: "2023-11-05" },
{ title: "Post 1", publishedAt: "2024-02-20" },
{ title: "Post 3", publishedAt: "2024-09-01" }
]
*/
To reverse the sort order:
posts.sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));
Sorting by date in JavaScript is straightforward with new Date()
and the sort()
method. Whether you’re sorting simple date strings or complex objects, this approach will keep your arrays in the correct chronological order.
If you enjoyed this article, I’d truly appreciate it if you could share it—it really motivates me to keep creating more helpful content!
If you’re interested in exploring more, check out these articles
- BDD Fundamentals with Jest and Cucumber
- Unit, Integration, and E2E Testing in One Example Using Jest
- Open-Closed Principle: The Hard Parts
- Isolation Levels In SQL Server With Examples
- Strategy vs State vs Template Design Patterns
Thanks for sticking with me until the end—I hope you found this article valuable and enjoyable!
Want more dev insights like this? Subscribe to get practical tips, tutorials, and tech deep dives delivered to your inbox. No spam, unsubscribe anytime.