alilland alilland - 1 year ago 74
Ruby Question

how would I sort an array of hashes by one value and then sort it again after that?

I have a massive array of hashes that I need to order by the numerical value of

after its sorted by
I need to sort it by

array = [
{job_num: 1236, date: Date.parse('2016/10/19')},
{job_num: 1234, date: Date.parse('2016/10/17')},
{job_num: 1236, date: Date.parse('2016/10/20')},
{job_num: 1233, date: Date.parse('2016/10/18')}
# => [{:job_num=>1236, :date=>#<Date: 2016-10-19 ((2457681j,0s,0n),+0s,2299161j)>}, {:job_num=>1234, :date=>#<Date: 2016-10-17 ((2457679j,0s,0n),+0s,2299161j)>}, {:job_num=>1236, :date=>#<Date: 2016-10-20 ((2457682j,0s,0n),+0s,2299161j)>}, {:job_num=>1233, :date=>#<Date: 2016-10-18 ((2457680j,0s,0n),+0s,2299161j)>}]

I need to first sort my array by

array.sort! { |x,y| x[:job_num] <=> y[:job_num] }
# => [{:job_num=>1233, :date=>#<Date: 2016-10-18 ((2457680j,0s,0n),+0s,2299161j)>}, {:job_num=>1234, :date=>#<Date: 2016-10-17 ((2457679j,0s,0n),+0s,2299161j)>}, {:job_num=>1236, :date=>#<Date: 2016-10-20 ((2457682j,0s,0n),+0s,2299161j)>}, {:job_num=>1236, :date=>#<Date: 2016-10-19 ((2457681j,0s,0n),+0s,2299161j)>}]

I then need it to sort by date after sorting by the job number, it should end up that the array looks like this if all goes well:

array = [
{job_num: 1233, date: '2016/10/18'},
{job_num: 1234, date: '2016/10/17'},
{job_num: 1236, date: '2016/10/19'},
{job_num: 1236, date: '2016/10/20'}

(I left off the date parse in the final array since its only an example and irrelevant to the logic)

Answer Source


array.sort_by! { |item| [item[:job_num], item[:date]] }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download