How to sort markdown blogs in astro by publish date?
First of all, all of your markdown blog files should have a publish date key in their frontmatter. You can choose any key name you want, I’m calling it pubDate
. And your date format should be like YYYY/MM/DD
, because later we need to convert it to an actual date object for sorting correctly, like so:
---
title: your_title
pubDate: 2023/12/25 // notice the date format, YYYY/MM/DD
---
By default, Astro.glob()
fetches files in an alphabetically sorted order and returns an array of those files. To sort the array before rendering, we will do the following:
// Fetch markdown files
const blogs = await Astro.glob("path/to/markdown/files");
// Sort the array in descending order (newest to oldest)
blogs.sort(
(a, b) =>
Date.parse(b.frontmatter.pubDate) - Date.parse(a.frontmatter.pubDate)
);
// Sort the array in ascending order (oldest to newest)
blogs.sort(
(a, b) =>
Date.parse(a.frontmatter.pubDate) - Date.parse(b.frontmatter.pubDate)
);
To sort the array, we’re using the sort()
method and providing a comparison function that determines the order of the elements.
Date.parse()
parses a string representation of a date and returns the date’s timestamp. We can sort the array in ascending or descending order. I’ve added the examples above for both orders.
Now we can render the sorted blogs array normally:
<ul>
{blogs.map((blog) => (
<li>
<a href={blog.url}>{blog.frontmatter.title}</a>
</li>
))}
</ul>
Tip: We can sort the array by other properties too, we would just need to add a key and value to the frontmatter of all the markdown files (like, order: 1
or page: 9
etc.) and sort them by that property in our astro file.