2016-10-20 73 views
0

我有散列的大規模陣列,我需要通過:job_num數值其通過:job_num排序之後訂購我需要:date我將如何對一個哈希值數組進行排序,然後再對它進行排序?

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)>}] 

我需要通過:job_num

第一排序我的數組排序它
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)>}] 

然後我需要它的日期由工號排序後進行排序,就應該結束了,數組看起來像這樣如果一切順利:

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離開的時間解析,因爲其僅是示例的最後陣列和無關的邏輯中)

+0

你可以發佈一些你的嘗試代碼嗎? – roelofs

回答

0

嘗試

array.sort_by! { |item| [item[:job_num], item[:date]] } 
0
array.sort! { |x,y| 
    by_job_num = x[:job_num] <=> y[:job_num] 
    by_job_num.zero? ? x[:date] <=> y[:date] : by_job_num 
} 
+0

儘管這段代碼可能會解決問題,但它並不能解釋爲什麼或如何回答問題。請[請爲您的代碼添加解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers),因爲這確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 **舉報人/評論者:** [僅限代碼解答,例如downvote,請勿刪除!](// meta.stackoverflow.com/a/260413/2747593) –

1

下面是使用Ruby枚舉sort_by方法的溶液:

#! /usr/bin/env ruby 

require 'date' 

puts "Sorting an array" 
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')}, 
] 

puts array 

array.sort_by! { |x| [ x[:job_num], x[:date] ] } 

puts 
puts array