Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group an array of hash by its value which has key-value pair in Ruby (Rails)?

So I have following array of hash:

my_array = [
  {
    "date" => "2022-12-01",
    "pic" => "Jason",
    "guard" => "Steven",
    "front_desk" => "Emily"
  },
  {
    "date" => "2022-12-02",
    "pic" => "Gilbert",
    "guard" => "Johnny",
    "front_desk" => "Bella"
  },
  {
    "date" => "2022-12-03",
    "pic" => "Steven",
    "guard" => "Gilbert",
    "front_desk" => "Esmeralda"
  }
]

My question is how do I change the structure of my array (grouping) by date in Ruby (Rails 7). Or in other word, I want to change my array into something like this:

my_array = [
  {
    "2022-12-01" => {
        "pic" => "Jason",
        "guard" => "Steven",
        "front_desk" => "Emily"
    {
  },
  {
    "2022-12-02" => {
      "pic" => "Gilbert",
      "guard" => "Johnny",
      "front_desk" => "Bella"
    }
  },
  {
    "2022-12-03" => {
      "pic" => "Steven",
      "guard" => "Gilbert",
      "front_desk" => "Esmeralda"
    }
  }
]

Anyway, thanks in advance for the answer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried using group_by method to group by its date, but it doesn’t give the output I wanted

I’ve tried this method:

my_array.group_by { |element| element["date"] }.values

>Solution :

If you simply want a 1:1 mapping of your input objects to an output object of a new shape, then you just need to use Array#map:

my_array.map {|entry| {entry["date"] => entry.except("date")} }

(Hash#except comes from ActiveSupport, and is not standard Ruby, but since you’re in Rails it should work just fine).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading