How to sort Product by discount percentage?

{% assign sortedProducts = collection.products | sort: ‘discountPercentage’ | reverse %}
{% for product in sortedProducts %}
{% assign discountPercentage = product.compare_at_price | minus: product.price | times: 100 | divided_by: product.compare_at_price | round %}
{% if product.available %}

{{ product.title }}

{{ product.price }}

Discount: {{ product.discountPercentage }}%

{% endif %} {% endfor %}

To sort products by their discount percentage, you can use the following code:

{% assign sortedProducts = collection.products | sort: 'discountPercentage' | reverse %}
{% for product in sortedProducts %}
  {% assign discountPercentage = product.compare_at_price | minus: product.price | times: 100 | divided_by: product.compare_at_price | round %}
  {% if product.available %}
    
      ### {{ product.title }}
      

{{ product.price }}

      

Discount: {{ discountPercentage }}%

    

  {% endif %}
{% endfor %}

Where should this code be placed?

Thanks