0

I have the following array:

[
  { id: 1, art: "art_123" },
  { id: 2, art: "art_234" },
  { id: 3, art: "art_123" }
]

I need to have the following output:

[
  { art: "art_123", ids: [1,3] }
  { art: "art_234", ids: [2] }
]

I've tried to group by "art" but I can't solve this. How to count total entries from every art?

jujajjjj
  • 55
  • 5
  • Other similar questions include: https://stackoverflow.com/questions/52538049/merge-an-array-of-hashes-by-key-value-pair https://stackoverflow.com/questions/11171834/merging-ruby-hash-with-array-of-values-into-another-hash-with-array-of-values https://stackoverflow.com/questions/24233493/merge-duplicates-in-array-of-hashes https://stackoverflow.com/questions/55370852/how-to-merge-two-hashes-with-same-id-by-combining-keys-with-different-values – engineersmnky Jul 14 '22 at 15:08
  • `arr.group_by {|c| c[:art]}.transform_values {|v| v.pluck(:id)}` – Crazy Cat Jul 15 '22 at 11:11

1 Answers1

1

The following is one way to obtain your desired result.

array = [{ id: 1, art: "art_123" },
         { id: 2, art: "art_234" },
         { id: 3, art: "art_123" }]
array.group_by { |hash| hash[:art] }
     .map do |k, v|
       { art: k, ids: v.map { |hash| hash[:id] } }
      end
  #=> [{ art: "art_123", ids: [1,3] },
  #    { art: "art_234", ids: [2] }]
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • Good answer. My main suggestion--a very minor one--is to make it more readable by writing the code on multiple lines (to which you alluded). I generally don't like editing answers but have done so here because I was unable to make my point clearly in a comment. Also I don't know why you said, "It is not pretty", as it's just fine, so I took that out. All that is purely a matter of style, however, so if you prefer to put your code on one line, or still think your code is ugly, by all means roll your answer back to what you had before or edit what I wrote. – Cary Swoveland Jul 14 '22 at 18:56