user122121 user122121 - 1 year ago 85
Ruby Question

Sort an array and make it unique on multiple conditions - Ruby

This is a sample array example as Input :

hashForAnimals = [{
:animalCd=>"Tiger",:animalType=>"Carnivore", :sortOrder =>3},
{:animalCd=>"Cow",:animalType=>"Herbivore", :sortOrder =>5},
{:animalCd=>"Rabbit", :animalType=>"Herbivore", :sortOrder =>2},
{:animalCd=>"Shark",:animalType=>"Carnivore", :sortOrder =>4},
{:animalCd=>"Cow",:animalType=>"Carnivore", :sortOrder =>1},
{:animalCd=>"Bear", :animalType=>"Omnivore", :sortOrder =>7},
{:animalCd=>"Tiger",:animalType=>"Carnivore", :sortOrder =>6}]

Expected Output:

hashForAnimals = [{
:animalCd=>"Cow", :animalType=>"Carnivore", :sortOrder =>1},
{:animalCd=>"Rabbit", :animalType=>"Herbivore", :sortOrder =>2},
{:animalCd=>"Tiger",:animalType=>"Carnivore", :sortOrder =>3},
{:animalCd=>"Shark",:animalType=>"Carnivore", :sortOrder =>4},
:animalCd=>"Cow", :animalType=>"Herbivore", :sortOrder =>5}
{:animalCd=>"Bear", :animalType=>"Omnivore", :sortOrder =>7}]

I need to sort the array on the basis of sort order and then I need to make the array unique with respect to animalCd falling under the same group i.e. animalType.

Tiger has appeared once with the minimum sort order, however Cow is appearing twice in the array but with different animalType.

It can be done by collecting the array into multiple animalType arrays and sorting and making them unique and merge back to a single array. However, I need an elegant solution for this.

Sample code that I'm trying:

hashForAnimals.sort!{|x,y| x[:sortOrder].to_i<=>y[:sortOrder].to_i}.group_by { |a| a[:animalType]}

I can group them into seperate hashes but then I need to make the individual hashes unique and then merge into the array.

Is this even possible in the way by which I'm approaching it?

Answer Source

you can use sort_by method and uniq and values_at

hashForAnimals.sort_by{ |a| a[:sortOrder] }.uniq{ |k| k.values_at(:animalCd, :animalType) }

# => [{:animalCd=>"Cow", :animalType=>"Carnivore", :sortOrder=>1}, {:animalCd=>"Rabbit", :animalType=>"Herbivore", :sortOrder=>2}, {:animalCd=>"Tiger", :animalType=>"Carnivore", :sortOrder=>3}, {:animalCd=>"Shark", :animalType=>"Carnivore", :sortOrder=>4}, {:animalCd=>"Cow", :animalType=>"Herbivore", :sortOrder=>5}, {:animalCd=>"Bear", :animalType=>"Omnivore", :sortOrder=>7}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download