List entries by category I have a number of entries that all belong under a Channel that I created. Each entry has a category field where the user can select one or many categories to associate the entry with. 

I am displaying these entries on my page, but would like to display each entry under the appropriate category.

For example, my entries are currently displayed like this:


Entry 1 (Category A)
Entry 2 (Category C)
Entry 3 (Category A)
Entry 4 (Category B)
Entry 5 (Category A)


I want it to display like this:


Entry 1 (Category A)
Entry 3 (Category A)
Entry 5 (Category A)
Entry 4 (Category B)
Entry 2 (Category C)


What's the best way to do this?
This will exclude empty categories, meaning they don't have any entries associated with them.

{% set entryIds = craft.entries.section('channelHandle').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).group('categoryGroupHandle') %}

{% for category in categories %}
    &lt;h2&gt;{{ category.title }}&lt;/h2&gt;
    &lt;ul&gt;
        {% set entries = craft.entries.section('channelHandle').relatedTo(category) %}
        {% for entry in entries %}
            &lt;li&gt;&lt;a href="{{ entry.url }}"&gt;{{ entry.title }}&lt;/a&gt;&lt;/li&gt;
        {% endfor %}
    &lt;/ul&gt;
{% endfor %}