Stefano Ortisi
Stefano Ortisi

Reputation: 5326

Order a hash array by an array key

I am trying to filter and reorder an array of hashes. The filter and the order is defined by another array of strings, which represent the value of the "slug" key of the hash. The resulting array should contain only the hashes whose value to the "slug" key is contained in the slugs array and ordered with the same order. If I have the first array as:

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"
  }
]

and the second array as:

ordered_keys = ["orange", "lemon", "strawberry"]

then, the result should be an array like this:

result = [
  {
    "slug" => "orange",
    "label" => "Orange Label"
  },
  {
    "slug" => "lemon",
    "label" => "Lemon Label"
  },
  {
    "slug" => "strawberry",
    "label" => "Strawberry Label"
  }
]

I managed to get just the filtering function with this:

result = data.select{|x| ordered_keys.include? x.slug}

but I cannot find a smart way to get the ordered one. Any ideas?

Upvotes: 4

Views: 368

Answers (1)

sawa
sawa

Reputation: 168101

Use map to translate your array of ordered keys into the corresponding hash. The order of the input array to map defines the order of the output array.

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

Upvotes: 11

Related Questions