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

萨拉瓦娜·库玛

我有一系列哈希:

[ 
  {
    :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

谁能帮我整理一下哈希数组?

卡里·斯沃夫兰
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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章