Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order a hash array by an array key

Tags:

arrays

ruby

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?

like image 211
Stefano Ortisi Avatar asked Dec 20 '22 06:12

Stefano Ortisi


1 Answers

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}}
like image 78
sawa Avatar answered Dec 30 '22 19:12

sawa