Is there a way to sort lists in Jekyll by two fields?
Asked Answered
L

2

15

Is there a way to sort lists by two fields with Jekyll/Liquid? For example, sorting first by year and then title. I have tried:

{% assign list = site.data.papers.papers | sort: 'year' | sort: 'title' %}

but that left it sorted only based on the last field, in this case the title. There was some discussion on this, but it seems to have been frozen without being merged: https://github.com/jekyll/jekyll/issues/1802

Thanks!

Leigha answered 12/8, 2017 at 15:12 Comment(0)
C
16

group_by to the rescue :

{% assign years = site.data.papers.papers | group_by: "year" %}
{% assign yearsSorted = years | sort: "name" %}
<ul>
{% for y in yearsSorted %}
  <li>{{ y.name }}
    <ul>
      {% assign yearTitlesSorted = y.items | sort: "title" %}
      {% for t in yearTitlesSorted %}
      <li>{{ t.title }}</li>
      {% endfor %}
    </ul>
  </li>
{% endfor %}
</ul>
Cubage answered 13/8, 2017 at 8:19 Comment(1)
That did the trick! Thank you very much for the group_by tip. The first two assignments could also be merged in your example ({% assign years = site.data.papers.papers | group_by: 'year' | sort: 'name' %}), but that does not change the fact that your code works.Leigha
D
2

If you start with a single array of hashes and you want to end up with the same array in the same structure (i.e. not grouped, just multi-sorted), use:

{% assign grouped = array | group_by: 'field1' %}
{% for item in grouped %}
   {% assign sorted = item['items'] | sort: 'field2' %}
   {% if forloop.first %}
      {% assign array = sorted %}
   {% else %}
      {% assign array = array | concat: sorted %}
   {% endif %}
{% endfor %}
Degraw answered 3/12, 2021 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.