order and limit the occurrences of related categories I'm generating a list of all related categories of the entries listed on the page.

{% for entry in entries %}
    {% set categories = craft.categories.group('functieGroep').level(2).relatedTo(entry).all() %}
    {% nav category in categories %}
        &lt;option value="{{ category.title }}"&gt;{{ category.title }}&lt;/option&gt;
    {% endnav %}
{% endfor %}


This produces the list of categories. However, I want this list sorted by category.title and only show one occurrence of similar listed categories?
As is mentioned in multiple places, Twig is for viewing, not manipulating data. However, this should work.

We create an empty array, then loop through each entry's categories and if they aren't in the array, add them. Then finish up with a sort by title

{% set categories = [] %}
{% for entry in entries %}
  {% set entryCategories = craft.categories.group...all() %}
   {# notice the IF to combat duplicates #}
   {% for category in entryCategories if category not in categories %}
     {% set categories = categories|merge([category]) %}
   {% endif %}
{% endfor %}
{% nav category in categories|sort((a,b) =&gt; { a.title &lt;=&gt; b.title } %} {# reverse to b.title &lt;=&gt; a.title to change sort #}
...
{% endnav %}