Sorting / ordering yaml data loops by a field

Hey All,

I’m looping through some YAML data to generate cards for a site I’m working on and just added a field called ‘order’ in which there is an integer I’d like to sort by.

I’m not much of a Rubyist and have tried various sort_by techniques, but am hitting a wall. Any help would be appreciated!

Iterator looks something like:

<% data.jobs.sort_by{:order}.each do |j| %>
    ...
<% end %>

I am actually having same problem. I have values like 1, 2, 3 and I want to sort them in descending order. Not sure how can I achieve it inside haml file.

You can do something like data.jobs.sort {|x,y| x.order <=> y.order}. Just change the position of x and y to sort the other way around basically.

This worked for me:

- data.yourdata.dataset.sort_by{|v| v.finalscore }.reverse.each_with_index do |item, index|
  - if item?
    .grid__item.palm--two-thirds.one-whole
      %a{href: "#{item.slug}"}
        =item.name
        =item.finalscore

Where finalscore is a value number and I want to display it in descending order.

@justshipit, is there any reason to use each_with_index instead of just each – you don’t seem to be using index-value anyway? And @tomrutgers’ comment (Just change the position of x and y to sort the other way around) is more efficient than additional reverse. Which might be unimportant if the dataset is not big.

2 Likes

Thanks for that! Appreciate your input :slight_smile: Just changed this part of code.

Why not use =link_to item.slug while we’re at it :smile:

2 Likes