⚠️ This lesson is retired and might contain outdated information.

Use sortBy to Sort Notes by Frontmatter Keys

Ben Hong
InstructorBen Hong
Share this video with your friends

Social Share Links

Send Tweet

Wouldn't it be nice to have an easy way to sort our notes so that they display in order of their published date? Nuxt gives us this with the sortBy function that we can chain onto fetch to sort by a specific frontmatter key by either descending or ascending. We are going to use the publishedOn key to be able to sort all of our notes in descending order so the newest one is displayed on top.

Instructor: [0:00] One of the things you might have noticed, though, when we see this list of notes, is that it's not sorted in any particular way. While you might be tempted to use a computer property to do that at first, Nuxt Content allows you an easy way to do that on the backend first, in order to save you some computation on the frontend.

[0:15] The way we do this is by adding a sortBy() function to our chain of commands when we're fetching our notes. SortBy takes two parameters. The first of which is the attribute that you want it to sort by, and then whether it's ascending or descending.

[0:28] In this particular case, we're going to sort by title. As you can see here now, it's alphabetical, with Egghead at top and View Components at the bottom. Then, if we go ahead and swap it to descending, you can see that View Components goes on top and then Egghead goes on bottom.

[0:40] However, since most digital gardens want to sort by chronological order, we want to sort by publishOn instead, because we want to sort by the date. As you can see here, this now allows us to sort it by most recent, which is descending. Then, we switch it to ascending, then it will do the oldest one at the top.

[0:57] For this course, let's go ahead and assume that people always want to read the most recent, so I'm going to swap it back to descending. Believe it or not, that's all it takes to sort your content using Nuxt Content.

[1:07] Before we wrap up this lesson, though, I want you to know, if we check out the docs and check out the Fetching Content section, you'll see that there are a bunch of other functions available to you, to better help sort or query and filter out the data before returning it to the client. I'll leave it to you to explore those functions in case you need them. I just want you to know that they're there for you.

[1:27] To recap, in this lesson, we've learned that you can chain additional functions to your content call so that it'll do the filtering in advance, rather than waiting to do it on the client side.