samedi 11 décembre 2021

Merging and grouping hashes value based on keys

I have an array of hashes (in this example 2 hashes, but there could be much more):

array = [
  { "answers"=>{
      "42"=>"61",
      "43"=>["0", "64", "0", "0", "66", "0"],
      "44"=>"It has always been pretty bad. None of the questions were answered properly.",
      "45"=>["0", "68", "0", "69", "0"]
    }
  },
  { "answers"=>{
      "42"=>"61”,
      "43"=>["0", "64", "0", "0", "66", "0", "67"],
      "44"=>"They are all amazing",
      "45"=>["0", "68", "0", "69", "0"]
    }
  }
] 

I would like to be able to merge the two hashes, group them by keys, and count the value per duplicated key.

The result would be something like :

{ "42" => ["61", 2],
  "43" => [
            [["64", "66"], 1],
            [["64", "66", "67"],1]
          ],
  "44" => [
            ["It has always been pretty bad. None of the questions were answered properly.",1],
            ["They are all amazing",1]
          ],
  "45" => [
            [["68", "69"],2]
          ]
}

Also note that:

  1. Certain values are arrays, of which the "0" have been removed during the process.
  2. The number following each array is the count of occurence.

Does anyone knows how to do this please? This is as far as I could get with the original data (active records)

Aucun commentaire:

Enregistrer un commentaire