How to Sort by Date in JavaScript?

Learn how to sort arrays of dates or objects with date fields in JavaScript using sort() and Date objects.

Introduction

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.

Sort an Array of Date Strings in JavaScript

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"]

Sort an Array of Objects by Date Field

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" }
]
*/

Descending Order: Most Recent First

To reverse the sort order:

posts.sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt));

Conclusion

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.

Think about it

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

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top