Last Updated: February 25, 2016
·
393
· neutralino1

Sort objets by N criteria

Ok imagine you need to sort an array of objects by N criteria.

Here's your array:

array = [{a: 2, b: 2}, {a: 2, b: 1}, {a: 1, b: 2}, {a: 1, b: 2}]

Here's the list of criteria:

criteria = [:a, :b]

And here's how to sort it:

array.sort! do |a,b| 
  criteria.reverse_each.inject(true) do |m, s|
    m && a[s] <=> b[s]
  end
end

And the result is

[{:a=>1, :b=>1}, {:a=>1, :b=>2}, {:a=>2, :b=>1}, {:a=>2, :b=>2}]

Cheers!