CMS Development

BRhea
Member

How to sort an array of numbers from lowest to highest with HubL?

I'm trying to create a programmable email that will make content recommendations to my contacts based upon some numerical values that are added to their account after they complete a lead generation form.

The values are nine scores that we assign to the contact record based on a self-assessment quiz they take on our site.

I want to take that array of scores and find the numbers that are the lowest so I can send a sequence of emails saying, "Hey, you're super low in X, take a look at our guide that addresses that specifically." Then wait a day and say, "Your next lowest score is Y. Here's a webinar we produced that will help!"

And so on.

My email content sets the array like so:

{% set array = [contact.val1, contact.val2, contact.val3, ...] %}

But I cannot find a filter or function in the HubL docs to order that array from smallest to largest so that I can pull array[0], array[1], etc.

Any thoughts? Thanks in advance!

0 Upvotes
2 Replies 2
webdew
Guide | Diamond Partner
Guide | Diamond Partner

How to sort an array of numbers from lowest to highest with HubL?

Hi @BRhea ,

Example 1 :
{% set array = [1, 3, 2, 5] %}
{% set decendingOrder = array|sort(True, False, '') %}
{{decendingOrder}}
{% set ascendingOrder = array|sort(False, True, '') %}
{{ascendingOrder}}

Example 2 :
{% set array = [{ "product": 1}, { "product": 3}, { "product": 2}, { "product": 5}] %}
// ascending order
{% set ascendingOrder = array|sort(False, True, 'product') %}
{{ascendingOrder}}
// decending order
{% set decendingOrder = array|sort(True, False, 'product') %}
{{decendingOrder}}


Hope this helps!


If we were able to answer your query, kindly help the community by marking it as a solution.

Thanks and Regards. 



piersg
Key Advisor

How to sort an array of numbers from lowest to highest with HubL?

Hi @BRhea, you want the sort filter. As an example, the below would give you 1, 3, 10, 100; you just need to make sure your values (contact.val1 etc) are numbers and not strings

 

{% set array = [3, 100, 1, 10] %}
{% for item in array|sort(False, False) %}
  {{item}}
{% endfor %}

 

 

If those values are strings, you would have to convert them to an integer first using the int filter in one of two ways:

 

{# method one: more programmatic #}
{% set array = ['3', '100', '1', '10'] %}
{% set newArr = [] %}
{% for item in array %}
  {% do newArr.append(item|int) %}
{% endfor %}
{% for item in newArr|sort(False, False) %}
  {{item}}
{% endfor %}

{# method two: less verbose but less flexible #}
{% set array = ['3'|int, '100'|int, '1'|int, '10'|int] %}
{% for item in array|sort(False, False) %}
  {{item}}
{% endfor %}