Sort by number of child tiddlers

Hello,

I believe it’s not a big problem, but I just can’t solve it.

I want to sort tiddlers by number of child tiddlers. Specifically, this is a wiki about my OCs, there are tiddlers of OC (tagged “OC”), and tiddlers of scanned image pages (tagged “imagepage”, and names of all mentioned OCs in that image (same as the OC tiddler title)). I want to know how many imagepage each OC have.

This is what I intuitively wrote:

<$vars pagestagging="[tag<currentTiddler>tag[imagepage]count[]]">
<table>
<tr><th>name</th><th>imagepage number</th></tr>
<$list filter="[tag[OC]sortsub:integer<pagestagging>]"><tr>
<td><$link to=<<currentTiddler>>/></td>
<td><$list filter=<<pagestagging>>>{{!!title}}</$list></td>
</tr></$list>
</table>
</$vars>

However, I got something like

name imagepage number
Aaron 1
Alice 3
Bob 1
Candice 5

The “pagestagging” filter worked in the second column, but the tiddlers are not sorted, they displayed by default alphabetical order.

How do I fix this?

Hello and welcome! Something like this should work — but modify as needed, and feel free to ask follow-ups:

<$let maxx={{{ [tags[]!is[system]] :map[tagging[]count[]] +[maxall[]] }}}>
<!-- the variable <<maxx>> (name it however you like!) marks the high-end of the possible count of tag-children, in your wiki. Its definition works by getting a list of non-system tags, and then using :map operator gets the count of each one, then selecting the maxall of those numbers. -->

<$list filter="[range<maxx>,[1]]" variable="descending-count">
<!-- starting with that maxx variable (highest count for tag-children), we count downward to 1, using range operator). Define <<descending-count>> to track the number we're at in this downward sequence… -->

<$list filter="""[tags[]!is[system]sort[]] :filter[tagging[]count[]match<descending-count>]""" variable="TagAtThisCount">
<!-- For the number we're currently at, we show tags whose count matches that number -->

<$tiddler tiddler=<<TagAtThisCount>> > <<tag>> </$tiddler><% if [<thisTag>]] %><<descending-count>> <% endif %>
<!-- For each tag, display whatever details you want... -->

</$list>
</$list>
</$let>

Thank you, Springer!
This filter was so much work for TidGi that it stopped working for several seconds, but it worked!