require 'pp'
ar = [
{"timestamp" => 1347119549, "category" => nil},
{"timestamp" => 1347119547, "category" => "Monkeys"},
{"timestamp" => 1347119543, "category" => nil},
{"timestamp" => 1347119542, "category" => "Monkeys"}
]
pp ar.group_by{|h| h['category'] ? h['category'] : h['timestamp']}.
map{|k,v| v.sort_by{|h| -h['timestamp']}}.
sort_by{|a| -a[0]['timestamp']}.flatten
# >> [{"timestamp"=>1347119549, "category"=>nil},
# >> {"timestamp"=>1347119547, "category"=>"Monkeys"},
# >> {"timestamp"=>1347119542, "category"=>"Monkeys"},
# >> {"timestamp"=>1347119543, "category"=>nil}]
require 'pp'
a = [
{"timestamp"=>1347119549, "category"=>nil},
{"timestamp"=>1347119547, "category"=>"Monkeys"},
{"timestamp"=>1347119543, "category"=>nil},
{"timestamp"=>1347119542, "category"=>"Monkeys"},
{"timestamp"=>1347119548, "category"=>"Dog"},
{"timestamp"=>1347119544, "category"=>"Dog"}
]
pp a.group_by{|h| h['category'] ? h['category'] : h['timestamp']}.
map{|k,v| v.sort_by{|h| -h['timestamp']}}.
sort_by{|a| -a[0]['timestamp']}.flatten
# >> [{"timestamp"=>1347119549, "category"=>nil},
# >> {"timestamp"=>1347119548, "category"=>"Dog"},
# >> {"timestamp"=>1347119544, "category"=>"Dog"},
# >> {"timestamp"=>1347119547, "category"=>"Monkeys"},
# >> {"timestamp"=>1347119542, "category"=>"Monkeys"},
# >> {"timestamp"=>1347119543, "category"=>nil}]