"Carnivore", :sortOrder =>3},-6ren">
gpt4 book ai didi

arrays - 对数组进行排序并使其在多个条件下唯一 - Ruby

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:40 24 4
gpt4 key购买 nike

这是作为输入的示例数组示例:

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}]

预期输出:

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}]

我需要根据排序顺序对数组进行排序,然后我需要使数组相对于属于同一组的 animalCd 是唯一的,即 animalType。

Tiger 以最小排序顺序出现了一次,但是 Cow 在数组中出现了两次,但动物类型不同。

可以通过将数组收集到多个 animalType 数组中并排序并使它们唯一并合并回单个数组来完成。但是,我需要一个优雅的解决方案。

我正在尝试的示例代码:

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

我可以将它们分组到单独的散列中,但随后我需要使各个散列唯一,然后合并到数组中。

这甚至有可能以我接近它的方式实现吗?

最佳答案

您可以使用sort_by 方法和uniqvalues_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}]

关于arrays - 对数组进行排序并使其在多个条件下唯一 - Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39497251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com