通过数组键排序哈希数组

时间:2013-04-22 17:53:31

标签: ruby arrays

我正在尝试过滤和重新排序哈希数组。过滤器和顺序由另一个字符串数组定义,这些字符串表示散列的"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}

但我找不到一种聪明的方法来获得有序的。有什么想法吗?

1 个答案:

答案 0 :(得分:11)

使用map将您的有序键数组转换为相应的哈希值。输入数组到map的顺序定义了输出数组的顺序。

ordered_keys.map{|k| data.find{|h| h["slug"] == k}}