我正在尝试过滤和重新排序散列数组。过滤器和顺序由另一个字符串数组定义,它们表示哈希的 "slug"
键的值。结果数组应仅包含其 "slug"
键的值包含在 slugs 数组中并以相同顺序排序的哈希。如果我有第一个数组:
data = [
{
"slug" => "lemon",
"label" => "Lemon Label"
},
{
"slug" => "table",
"label" => "Table Label"
},
{
"slug" => "peach",
"label" => "Peach Label"
},
{
"slug" => "strawberry",
"label" => "Strawberry Label"
},
{
"slug" => "bread",
"label" => "Bread Label"
},
{
"slug" => "orange",
"label" => "Orange Label"
}
]
和第二个数组为:
ordered_keys = ["orange", "lemon", "strawberry"]
然后,结果应该是这样的数组:
result = [
{
"slug" => "orange",
"label" => "Orange Label"
},
{
"slug" => "lemon",
"label" => "Lemon Label"
},
{
"slug" => "strawberry",
"label" => "Strawberry Label"
}
]
我设法通过以下方式获得了过滤功能:
result = data.select{|x| ordered_keys.include? x.slug}
但我找不到一种聪明的方法来获得订购的。有任何想法吗?
最佳答案
使用 map
将有序键数组转换为相应的哈希。 map
的输入数组的顺序定义了输出数组的顺序。
ordered_keys.map{|k| data.find{|h| h["slug"] == k}}
关于ruby - 按数组键排序散列数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16153553/