Home > OS >  How to sort loop based on response value from array
How to sort loop based on response value from array

Time:09-17

So below is a small structure how I loop items, I want to sort them in my loop from by amount of members to smallest, instead of it being randomly displayed? How should I approach this? Also, if loop contains only 2 elements, how can I set display div to none?

    <% for item in @items %>

<%= item.name %>
<%= item.members %>

<% end %>

CodePudding user response:

You could try:

<% if @items.size > 2 %>
  <div>
    <% @items.sort_by { |item| item.members.size }.each do |item| %>
      <%= item.name %>
      <%= item.members %>
    <% end %>
  </div>
<% end %>
  • Related