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!
Written by Emmanuel Turlay
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#