CMS Development

jonflynnh2o
Participant | Partner
Participant | Partner

Sort array of dictionaries by attribute in hubl

SOLVE

Hi, say I have an array like so:

[{ "example_key": "example", "order": 1},  { "example_key": "example", "order": 3}, { "example_key": "example", "order": 1}, { "example_key": "example", "order": 5}]

 

I'm looking to sort these in reverse order by their attribute 'order' using hubl. How can this be achieved?

0 Upvotes
1 Accepted solution
Ntbrown
Solution
Contributor

Sort array of dictionaries by attribute in hubl

SOLVE

Per the sort filter you can specify an attribute. Dicts are just objects. As `sort` is applied it's inherently going over the list, as any sorting algorithm must, and the attribute will be applied to the current element (in this case a dict object). So, supply the `order` as the attribute to sort by.... Similarly, just flip the order per the other argument(s) available.

 

{% set array = [{ "example_key": "example", "order": 1},  { "example_key": "example", "order": 3}, { "example_key": "example", "order": 1}, { "example_key": "example", "order": 5}] %}

{% set reverseOrder = array|sort(True, False, 'order') %}

 

Easy. The hard part is how are you determining order if there are duplciates as in your listing? That's rather contradictory to what the attribute is named and isn't well-defined ;).

View solution in original post

0 Upvotes
2 Replies 2
Ntbrown
Solution
Contributor

Sort array of dictionaries by attribute in hubl

SOLVE

Per the sort filter you can specify an attribute. Dicts are just objects. As `sort` is applied it's inherently going over the list, as any sorting algorithm must, and the attribute will be applied to the current element (in this case a dict object). So, supply the `order` as the attribute to sort by.... Similarly, just flip the order per the other argument(s) available.

 

{% set array = [{ "example_key": "example", "order": 1},  { "example_key": "example", "order": 3}, { "example_key": "example", "order": 1}, { "example_key": "example", "order": 5}] %}

{% set reverseOrder = array|sort(True, False, 'order') %}

 

Easy. The hard part is how are you determining order if there are duplciates as in your listing? That's rather contradictory to what the attribute is named and isn't well-defined ;).

0 Upvotes
jonflynnh2o
Participant | Partner
Participant | Partner

Sort array of dictionaries by attribute in hubl

SOLVE

Thanks. Will try this soon. Yep, just realized that the attribute is badly named, was only using it for an example for this post. In the real scenario, we're using larger objects and going by a relevance score to sort them.

0 Upvotes