简体   繁体   中英

Collect unique elements from array of hashes in Ruby

I have this data:

   [
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      0
   ],
   [
      {
         "identifier"=>"A",
         "inclusion"=>true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      1
   ],
   [
      {
         "identifier"=>"B",
         "inclusion"=>"true",
         "name"=>"ALK",
         "specific"=>"false"
      },
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      4
   ],
   [
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      5
   ]
]

I am trying to extract unique elements based on the key 'identifier' reserving the index already stored

I would want the output like this

   [
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      0
   ],
   [
      {
         "identifier"=>"B",
         "inclusion"=>"true",
         "name"=>"ALK",
         "specific"=>"false"
      },
      {
         "identifier"=>"A",
         "inclusion"=>"true",
         "name"=>"FGFR2",
         "specific"=>"false"
      },
      4
   ]
]

I tried a couple of ways using map, each_with_index and also map_with_index but they are not working as expected.

Could someone please help me.

I'm sure it can be greatly improved by the Ruby expert here but here is a code that should do what you want:

  • array is the name of your intial array of array
  • I then create a copy of this array , keeping only the Identifier. array2 = [["A"], ["A"], ["B", "A"], ["A"]]
  • And then I iterate over the array and, for each element, check if the first position of this element in array2 is equal to the current position in array2 .
array = [[{"identifier" => "A"...},0]...]

array2 = array.map { |arr| arr.map { |obj| obj.is_a?(Hash) ? obj['identifier'] : nil }.compact }

array.each_with_index.map { |arr, i| array2.index(array2[i]).eql?(i) ? arr : nil }.compact

# [[{"identifier"=>"A", "inclusion"=>"true", "name"=>"FGFR2", "specific"=>"false"}, 0], [{"identifier"=>"B", "inclusion"=>"true", "name"=>"ALK", "specific"=>"false"}, {"identifier"=>"A", "inclusion"=>"true", "name"=>"FGFR2", "specific"=>"false"}, 4]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM