List of pages in a section grouped by first taxonomy term

I would like to list pages of a section with specific ordering determined by taxonomy terms and weight.

The taxonomy is topics, each page currently can have multiple terms set, but the first one is decisive for its ordering (in its section).

It sounds all very simple, each such section would define a Param that would affect the ordering of pages within, e.g.:

params:
  topics:
  - a
  - b

There are NOT the terms, this is meant to affect ordering of pages in the section list.

Now all pages that have first topics term set as a should be listed before pages that have first topics term set as b.

I got myself into constructs like this when making the test list.html now:

{{ $topics := slice "a" "b" "c" }}
{{- $pages := $.Pages -}}
{{- $xpages := where $pages "(index (.GetTerms 'topics') 0).Name" "in" $topics -}}

And of course it does not work.

Not sure if I managed to explain the intention clearly, but basically say a section with 3 pages that list their topics terms as [b,x,y,z], [a,p,q,r], [b,u,v,w] and have the taxonomy weights 4 (in b), 2 (in a), 3 (in b) should be ordered as: 2,3,1 due to the first topics term each page has and the taxonomy weight the “equals” with b term have.

Has anyone done something similar? Thanks a lot.

FWIW A quick’n’dirty solution was:

{{ range .Params.topics }}
  ...
  {{ $topicgroup := . }}
  ...
  {{ range $.Pages }}
    {{ $topic := (index (.GetTerms "topics") 0).Name }}
    {{ if eq $topic $topicgroup }}
      {{ partial ... }}
    {{ end }}
  {{ end }}
{{ end }}

And then with the sorting - would be second range before the partial is called.

Not sure if there’s anything more efficient.