0

I'm making a photo gallery/lightbox and am using graphql to manage the pictures.

I have 10 photos in a folder: "1- Picture.png", "2- Picture of other thing.png", "3-...", ..., "10- My last picture.png"

I'm using the following snippet to sort in ascending order,

export const query = graphql`
  query($gallery: String!) {
    allFile(
      filter: {
        sourceInstanceName: { eq: "galleries" }
      absolutePath: { glob: $gallery }
      }
      sort: { fields: name, order: ASC }
    ) {
      nodes {
        name
        childImageSharp {
          fluid(maxWidth:1920, quality:90) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
`

But the output order is "1- Picture.png", "10- My last picture.png", "2- Picture of other thing.png",...

Is there an intelligent way to sort by the number at the start of the string? The easiest way I can think of is to rename the 1-9 files "01-...png", but I'm trying to implement this for several thousand folders of 5-150 photos, all with this "1-" naming convention.

How do I sort these photos such that "9- Some name.png" is listed before "10- My last picture.png"?

nicholas
  • 180
  • 2
  • 9
  • It might just make sense to rename the files. – ksav Oct 23 '19 at 19:08
  • @ksav I'm beginning to lean that way. I feel this should be manageable though - I _think_ the logic behind what I want to do is reasonable. – nicholas Oct 24 '19 at 03:35
  • Sure anything is possible. But like you said, it's going to be way easier to find a way to batch rename all your files and pad the filenames with leading 0s. – ksav Oct 24 '19 at 07:17

2 Answers2

1

I had the same issue, technically speaking 11 comes before 2 because the sort is alphabetical and 1 comes before 2. The sort is based on the first character then characters after if it needs it in the sort.

The solution is to rename 1-9 to 01-09 that way 0 comes before 1.

aidan22
  • 69
  • 1
  • 10
0

I could not sort the result by query, but I decided same question with sorting by a number in a string, by sorting the resulting array of objects:

queryResult.sort(function(a,b){
  return Number(b.PriceString) - Number(a.PriceString);
});