Skip to content

Keep groups in order of grouped items #7628

@timroes

Description

@timroes

Currently when using the group operator the returned groups are sorted by the fieldValue i.e. the grouped term. I think that's a confusing default behavior and the default behavior should rather: keep the order that the original items had, since these items might have been sorted by using the sort parameter.

Example

If the original items where in the following order and all having a g field with the following values:

  • Item 1 (g=B)
  • Item 2 (g=B)
  • Item 3 (g=A)
  • Item 4 (g=C)
  • Item 5 (g=A)

I would expect the group(field: g) query to return the following order:

  • B
    • Item 1
    • Item 2
  • A
    • Item 3
    • Item 5
  • C
    • Item 4

I.e. it should return group B first, because the first item was in that group (and of course keep the order of items within each group).

Use-Case

On the home page I would like to show my blog posts grouped by category, but the category with the most recent posts always on top. So I am using the following query:

{
  allMarkdownRemark(sort: { fields: frontmatter___date, order: DESC }) {
    categories: group(field: frontmatter___category) {
      name: fieldValue
      posts: edges {
        node {  ... }
      }
    }
  }
}

Unfortunately that does not work, since the grouping inside the query destroys the original order of posts. I think the default behavior of the group should be to keep the groups in the order the child items had been after the sort.

Distinction of other issues

There is some overlap with #5046 and #3684, which are wishing for an explicit option to sort groups. I think that would be a nice addition too, and THAT sorting option should be the place you should use to sort by grouping key. In distinction this issue should track the suggestion of NOT destroying the orders of items by grouping (independent of a possible group sorting option).

Metadata

Metadata

Labels

status: needs reproductionThis issue needs a simplified reproduction of the bug for further troubleshooting.topic: GraphQLRelated to Gatsby's GraphQL layertype: bugAn issue or pull request relating to a bug in Gatsby

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions