[英]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: 我想按以下顺序对其进行排序:
to
首先排序是基于to
from
第二类是基于from
organisation name
第三类基于organisation name
title
最后,根据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 . 请参见Array#<=> ,尤其是文档的第三段,以及Enumerable#sort_by 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.