How to sort a nested array?

I have an .yml like this

A:
  - a:1
  - b:2
B:
 - a:2
 - b:1

how to use liquid forloop sort this file by a or b? such that i could have the following?

B:
 - a:2
 - b:1

A:
  - a:1
  - b:2

Thanks.

You mean nested hashes not arrays.

You could rewrite your data with a fixed order using arrays.

- name: A
  values:
   - a: 2
   - b: 1
- name: B
  ...

Then you can iterate over the outer level, then iterate over the items in values. You can use the reversed filter. Or just fix your data to be in that reversed order, though I understand you might want to only reverse sometimes so the filter is good for that.

If you keep your data structure as is, you’ll have to apply sort filter on A, B keys.

Can you provide any existing code to make it easier to help? Just getting for loop right an array or unpacking keys and values is enough of a question by itself and I can’t tell how far you got with that. Sorting and reversing would be second level of complexity