[英]Sort or map two arrays in ruby
I have a section array ['part one','part two']
and an array of item objects [item1,item2,item3]
. 我有一个节数组['part one','part two']
和项目对象数组[item1,item2,item3]
。
Each item object has a section attribute ( in this case with the value of 'part one' or'part two') and an order attribute which is an integer. 每个项目对象都有一个section属性(在这种情况下,其值为'part one'或'part two')和一个order属性,该属性是一个整数。
I want to create an array like 我想创建一个数组
[ ['part one',[item1,item3]],['part two',[item3]] ]
or 要么
[['part one',item1,item3],['part two',item3]]
where 哪里
item1.section == 'part one' and item1.order == 1,
item3.section == 'part one' and item3.order == 2,
item2.section == 'part two' and item2.order == 1
To group by section
, and order by order
you can do the following: 要按section
分组和按order
您可以执行以下操作:
items.sort_by(&:order).group_by(&:section).to_a
# => [["part one", [item1, item3]], ["part two", [item2]]]
sort_by
orders all the items according to the order
attribute, while group_by
groups them into a hash of arrays, each key is a different section
. sort_by
根据order
属性对所有项目进行order
,而group_by
将它们分组为一个数组的哈希,每个键是一个不同的section
。 to_a
turns the hash into an array. to_a
将哈希值转换为数组。
If you want to keep the order of the section
list, you can use it to define the order instead of to_a
: 如果要保留section
列表的顺序,可以使用它来定义顺序,而不是to_a
:
grouped = items.sort_by(&:order).group_by(&:section)
# => { "part one" => [item1, item3], "part two" => [item2] }
sorted = sections.zip(sections.map { |s| grouped[s] })
# => [["part one", [item1, item3]], ["part two", [item2]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.