How to sort a Trie.filter result?

Hi, I would like to sort the result of a Trie.filter result.

This is my function:

// Get all articles by category
public query func getArticlesByCategory (artCategory : Text) : async [ArticleCatWithId] {
// func filter<K, V>(t : Trie<K, V>, f : (K, V) → Bool) : Trie<K, V>
let result : Trie.Trie<ArtId, Article> = Trie.filter<ArtId, Article>(articles, func (k, v) { v.artCategory == artCategory });
Trie.toArray<ArtId, Article, ArticleCatWithId>(result, transformCategory);

Is there a way to sort the result by a property name? The title of the article e.g.?

Thanks for any help.

You’ll have to roll your own sort function for now, I think we couldn’t quite decide which flavour of sort we wanted to include in the base libraries.

There’s a quicksort implementation in the examples here:


Hi, thanks for pointing this out. The quick sort example is about sorting integers, so we have to adopt it.

One other solution, more easier, would be to sort the resulting array in the frontend application via Javascript.

Not quite. The example sorts integers but the actual function is generic and works for any type. Not sure it’s the best implementation though and not randomized as it should be.

I will try it, but for most use cases the sorting would be better on the client site.

On other question regarding cycles would be, can an intensive sorting process increase the costs of running the canister?

Yes. And a worse algorithm might also exceed the finite cycle budget allowed per call.

FWIW I just added an implementation of merge sort for arrays to base: Adds a merge-sort for Arrays by kritzcreek · Pull Request #256 · dfinity/motoko-base · GitHub

Should be available with the next dfx update (or immediately with vessel if you can’t wait :wink: )