4

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?

0

1 Answer 1

11

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}}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! That's exactly what I was looking for. A smart and concise way to get the result. Awesome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.