How do I sort an array of dictionaries by more than one key?

Let’s say I have the following array:

#let arr = (
  (a: "foo", b: "not bar", c: "baz"),
  (a: "qux", b: "quux", c: "corge"),
  (a: "fizz", b: "buzz", c: "fizzbuzz"),
  (a: "foo", b: "bar", c: "baz"),
)

I now want to sort this array fist by the key a of the contained dictionary and then by the key b. using #arr.sorted(key: it => it.a) only sorts by the first key. If they are the same, like in line 1 and 4, I then want to sort by key b within this subgroub, such that the result would be:

(
  (a: "fizz", b: "buzz", c: "fizzbuzz"),
  (a: "foo", b: "bar", c: "baz"),
  (a: "foo", b: "not bar", c: "baz"),
  (a: "qux", b: "quux", c: "corge"),
)

How can I achieve this sorting?

You can give a tuple for the key.

#arr.sorted(key: it => (it.a, it.b))

You can also give a sum of a and b for the key.

#arr.sorted(key: x => x.a + x.b)

But I think a sorted function with custom compare function will be better. Unfortunately it’s not supported yet, but there’s already an issue.

1 Like

nice! I think the docs should be updated to mention this possibility. If I find the time I’ll create a PR

1 Like

Add documentation example to `array.sorted()` by nineff · Pull Request #5475 · typst/typst · GitHub is merged!

1 Like