Omitting unused letters from A to Z list I'm displaying lists of members grouped by their surname initial which the user navigates using a list of letters from A to Z. This part was straightforward enough and the following code works to return all members with a particular initial.

{% set searchString = 'surname:' ~ searchLetter ~ '*' %}
{% set members = craft.entries.section('members').search(searchString).order('surname', 'firstName') %}


Where I'm struggling is listing only the letters for which there are members to use for navigation, or to be able to list them all but disable those that don't have members.

Currently I just loop over the characters in the alphabet and output all of them.

{% set characters = 'a'..'z' %}


If someone clicks on a letter that has no members they get a blank list, but this isn't ideal as it would be better if there wasn't a link to this page.

I know with SQL I could do something like a SELECT DISTINCT with grouping to return just a list of initials in use, but is this possible with Twig or would I need to look at writing a plugin?
[untested]

Something like this should do the trick:

{% for letter, members in craft.entries.section('members').order('surname', 'firstname') | group('surname|slice(0,1)') %}
    &lt;h1&gt;{{ letter }}&lt;/h1&gt;
    &lt;ul&gt;
    {% for member in members %}
        &lt;li&gt;{{ member.surname }}, {{ member, firstname }}&lt;/li&gt;
    {% endfor %}
    &lt;/ul&gt;
{% endfor %}