How to make an index by letter?

I have a long list of pages:

<div class="recipe-list">
  {% for recipe in site.recipes %}
  <div class="recipe-item">
    <a href="{{ recipe.url }}">{{ recipe.title }}</a>
  </div>
  {% endfor %}
</div>

Since this list is long (~500) items, I want to index it by letters. That is, I want at the top of the list to be a list of letters A-Z which are then internal links that will scroll the user to the first item that starts with the given letter. Or if no items start with that letter, then take the user to the first item that starts with the next letter.

I think what I need to do is to first create a list of anchors to #a, #b, #c, and so on.

Then I guess I will need to edit the above code to generate the list such that it inserts hidden elements in the list first time it encounters an item that begins with letter A and so on…

And if there are letters that do not have an item starting with it, it would just output those when it comes to the letter that is after… Example, lets say we have item “Alpha”, so it outputs the #a anchor and the Alpha item. Then next item is “Charlie” so no items starting with B. So it would need to output both anchor for #b and for #c.

Is this the right approach?

Is there an easier way to do this?

This ended up working:

<div class="letter-list">
    <ul>
        {% assign letters = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,Æ,Ø,Å" | split: "," %}
        {% for letter in letters %}
            <li><a href="#section-beginswith-{{ letter }}">{{ letter }}</a></li>
        {% endfor %}
    </ul>                                                                                                                    </div>
<ul class="recipe-list">
    {% for letter in letters %}
        <a id="section-beginswith-{{ letter }}"></a>
        {% for recipe in site.recipes | sort: 'title' %}
            {% assign first_letter = recipe.title |slice: 0, 1 | upcase %}
            {% if first_letter == letter %}
                <li class="recipe-item">
                    <a href="{{ recipe.url }}">{{ recipe.title }}</a>
                </li>
            {% endif %}
        {% endfor %}
    {% endfor %}
</ul>