#sorting a content collection

3 messages · Page 1 of 1 (latest)

formal thicket
#

I can't seem to sort a collection in the frontmatter.

const products = (await getCollection("products"))
.sort((a, b) => a.data.title.valueOf() - b.data.title.valueOf())

Looping through the above still gives me an array sorted by the slug.

leaden shardBOT
#

Hi @formal thicket. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

It seems like you're trying to sort a collection based on the title. However, the valueOf() method you're using is typically for JavaScript Number and Date objects, and it might not work as expected with string values like your titles.

Instead, you can use the localeCompare() method which is used to compare two strings in the current locale. Here's how you can do it:

const products = (await getCollection("products"))
  .sort((a, b) => a.data.title.localeCompare(b.data.title));

This will sort your products collection in ascending order based on the title. If you want to sort in descending order, you can simply swap a and b:

const products = (await getCollection("products"))
  .sort((a, b) => b.data.title.localeCompare(a.data.title));

You can find more information about sorting collections in the Astro documentation (https://docs.astro.build/en/guides/content-collections#filtering-collection-queries).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: