How to sort Product by discount percentage?

Anil-pawn
Visitor
1 0 0

{% 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 %}
<div class="product"> <h3>{{ product.title }}</h3> <p>{{ product.price }}</p> <p>Discount: {{ product.discountPercentage }}%</p> </div>
{% endif %}
{% endfor %}
</div>
</div>

Reply 1 (1)

NomtechSolution
Astronaut
1245 113 149

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 %}
    <div class="product">
      <h3>{{ product.title }}</h3>
      <p>{{ product.price }}</p>
      <p>Discount: {{ discountPercentage }}%</p>
    </div>
  {% endif %}
{% endfor %}