在ruby中对两个数组进行排序或映射

时间:2021-12-06 14:04:48

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.

每个item对象都有一个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

1 个解决方案

#1


3  

To group by section, and order by order you can do the following:

要按部分分组,并按订单排序,您可以执行以下操作:

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. to_a turns the hash into an array.

sort_by根据order属性对所有项进行排序,而group_by将它们分组为数组的散列,每个键是不同的部分。 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:

如果要保持部分列表的顺序,可以使用它来定义顺序而不是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]]]

#1


3  

To group by section, and order by order you can do the following:

要按部分分组,并按订单排序,您可以执行以下操作:

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. to_a turns the hash into an array.

sort_by根据order属性对所有项进行排序,而group_by将它们分组为数组的散列,每个键是不同的部分。 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:

如果要保持部分列表的顺序,可以使用它来定义顺序而不是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]]]