Search code examples
arraysrubyhashgroupingruby-on-rails-7

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

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).