#How can I sort a collection?

4 messages · Page 1 of 1 (latest)

tame summit
#

I have three items in my collection (building a portfolio), but I would like the third item to be in the place of a second one. I read through the docs but couldn't find anything related to sorting.. Any tips of where I could look to make this happen are welcome.

merry axle
#

You can call .sort on the array returned from getCollection and compare them using something like the frontmatter data.

const entries = await getCollection('blog')

// sort new > old
entries.sort((a, b) => {
  return b.data.publishedAt.getTime() - a.data.publishedAt.getTime()
})
tame summit
#

@merry axle Thank you so much! 🙂

slate wagon
#

Every once in a while (because something like WordPress does things like this for you or makes it easy for you to do so with "posts") someone wonders about things like this. Maybe time the Content Collections doc give all these options... they're all non-Astro js, yeah, but would sure come in handy