Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It looks a little ugly, but it works:</p> <pre><code>a = [ {"timestamp"=&gt;1347119549, "category"=&gt;nil}, {"timestamp"=&gt;1347119547, "category"=&gt;"Monkeys"}, {"timestamp"=&gt;1347119543, "category"=&gt;nil}, {"timestamp"=&gt;1347119542, "category"=&gt;"Monkeys"}, {"timestamp"=&gt;1347119548, "category"=&gt;"Dog"}, {"timestamp"=&gt;1347119544, "category"=&gt;"Dog"} ] groups = a.sort_by {|h| -h['timestamp']}.group_by {|h| h['category']} sorted = (groups.delete(nil) || []) + groups.values sorted = sorted.sort_by{|i| i.is_a?(Hash) ? -i['timestamp'] : -i.first['timestamp']}.flatten </code></pre> <p>This gives you the following in <code>sorted</code>:</p> <pre><code>[ {"timestamp"=&gt;1347119549, "category"=&gt;nil}, {"timestamp"=&gt;1347119548, "category"=&gt;"Dog"}, {"timestamp"=&gt;1347119544, "category"=&gt;"Dog"}, {"timestamp"=&gt;1347119547, "category"=&gt;"Monkeys"}, {"timestamp"=&gt;1347119542, "category"=&gt;"Monkeys"}, {"timestamp"=&gt;1347119543, "category"=&gt;nil} ] </code></pre> <p>I sort first by <code>'timestamp'</code>, so that the groups are sorted later.</p> <p>After grouping by <code>'category'</code>, I move the values of the <code>nil</code> category in an array. Here, I use <code>(groups.delete(nil) || [])</code> in case the <code>nil</code> group is empty.</p> <p>Now it can be sorted by <code>'timestamp'</code> again, with the <code>timestamp</code> of an array being the <code>timestamp</code> of its first hash.</p> <p>Finally <code>flatten</code> gives us the desired array.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload