简体   繁体   中英

Sorting array of hashes based on multiple values

I have an array of hashes:

[ 
  {
    :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"
  }
]

I want to sort it in the following order:

  1. First sort is based on to
  2. Second sort is based on from
  3. Third sort is based on organisation name
  4. Finally, sort based on title

Can anyone help me sort the array of hashes?

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

See Array#<=> , particularly the third paragraph of the doc, and Enumerable#sort_by .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM