Looping through a list

I have a list containing maps that I want to loop through.

[
  %{book_type: "Fiction", total: 5},
  %{book_type: "History", total: 45},
  %{book_type: "Romance", total: 90},
  %{book_type: "Drama", total: 7}
]

i want to loop on this html tds

          <tr>
             <td class="text-left border-top" style="font-weight: normal !important;">books</td>
             <td class="border-top"style="font-weight: normal !important;">Fiction</td>
             <td class="border-top"style="font-weight: normal !important;">History</td>
             <td class="border-top"style="font-weight: normal !important;">Romance</td>
             <td class="border-top"style="font-weight: normal !important;">Drama</td>
          <tr>
          <td style="font-weight: normal !important;">Total</td>
           <%= for book <-@books do %>
             <td style="font-weight: normal !important;"><%= book.total %></td>
             <td style="font-weight: normal !important;"><%= book.total %></td>
             <td style="font-weight: normal !important;"><%= book.total %></td>
             <td style="font-weight: normal !important;">0<%= book.total %></td>
             <% end %>
          </tr>

I want to produce something like this

books Fiction History Romance Drama
Total 5 45 90 7

how do I go about it?

Your question isn’t very clear, but I think your desired output is the table with corresponding book_types to totals. Maybe using two loops, like this:

<tr>
  <td style="font-weight: normal !important;">Books</td>
   <%= for book <- @books do %>
     <td style="font-weight: normal !important;"><%= book.book_type %></td>
   <% end %>
</tr>
<tr>
  <td style="font-weight: normal !important;">Total</td>
   <%= for book <- @books do %>
     <td style="font-weight: normal !important;"><%= book.total %></td>
   <% end %>
</tr>

will achieve that.

1 Like

Aside from the question of how to do this specific task, it might help if you try to get out of the “looping over” mindset. That’s more of an imperative thing, inherited (so to speak) by object-oriented languages as well. Functional languages like Elixir don’t usually loop in quite the same sense of being able to do arbitrary things to the individual items and the collection. They more commonly map and filter and reduce. (Though these sometimes go by other names, like collect and select and inject. Sorry, Arlo, no infect or neglect.)