基于多个值对哈希数组进行排序

时间:2018-07-31 02:13:21

标签: ruby sorting

我有一个哈希数组:

[ 
  {
    :title=>"Working as a SSE",
    :organisation=>{:id=>428, :name=>"google"},
    :from=>"2018-6-1",
    :to=>nil
  }, {
    :title=>"Concatenate two video files to single video in players",
    :organisation=>{:id=>197, :name=>"UNFPA"},
    :from=>"2014-1-1",
    :to=>"2015-12-1"
  }, {
    :title=>"Highcharts Demo",
    :organisation=>{:id=>6, :name=>"UNDFS"},
    :from=>"2016-1-1",
    :to=>"2017-6-1"
  }, {
    :title=>"Working as a Judicial Affairs",
    :organisation=>{:id=>427, :name=>"swtp"},
    :from=>"2017-1-1",
    :to=>"2018-6-1"
  }
]

我想按以下顺序对其进行排序:

  1. 第一类基于to
  2. 第二种排序基于from
  3. 第三种排序基于organisation name
  4. 最后,根据title
  5. 进行排序

任何人都可以帮助我对哈希数组进行排序吗?

1 个答案:

答案 0 :(得分:8)

arr = [ 
  {
    :title=>"Working as a SSE",
    :organisation=>{:id=>428, :name=>"google"},
    :from=>"2018-6-1",
    :to=>"2017-6-1"
  }, {
    :title=>"Concatenate two video files to single video in players",
    :organisation=>{:id=>197, :name=>"UNFPA"},
    :from=>"2014-1-1",
    :to=>"2015-12-1"
  }, {
    :title=>"Highcharts Demo",
    :organisation=>{:id=>6, :name=>"UNDFS"},
    :from=>"2016-1-1",
    :to=>"2017-6-1"
  }, {
    :title=>"Working as a Judicial Affairs",
    :organisation=>{:id=>427, :name=>"swtp"},
    :from=>"2017-1-1",
    :to=>"2018-6-1"
  }
]

arr.sort_by { |h| [h[:to], h[:from], h[:organisation][:name], h[:title]] }
  #=> [{:title=>"Concatenate two video files to single video in players",
  #     :organisation=>{:id=>197, :name=>"UNFPA"},
  #     :from=>"2014-1-1",
  #     :to=>"2015-12-1"},
  #    {:title=>"Highcharts Demo",
  #     :organisation=>{:id=>6, :name=>"UNDFS"},
  #     :from=>"2016-1-1",
  #     :to=>"2017-6-1"},
  #    {:title=>"Working as a SSE",
  #     :organisation=>{:id=>428, :name=>"google"},
  #     :from=>"2018-6-1",
  #     :to=>"2017-6-1"},
  #    {:title=>"Working as a Judicial Affairs",
  #     :organisation=>{:id=>427, :name=>"swtp"},
  #     :from=>"2017-1-1",
  #     :to=>"2018-6-1"}]

请参见Array#<=>(尤其是文档的第三段)和Enumerable#sort_by