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

标签 arrays ruby sorting

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

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 数组中并排序并使它们唯一并合并回单个数组来完成。但是,我需要一个优雅的解决方案。

我正在尝试的示例代码:

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/

相关文章:

python 如何在不从列表中删除元素的情况下按出现次数对列表进行排序?

ios - 为什么从 NSMutableArray 设置 labels.text 不起作用?

java - java 二维数组求最后一行的平均值

javascript - link_to 为 :method => :delete routing through GET not DELETE rails 4

php - 对数组进行排序 - 数字、特殊字符、字母

algorithm - 为什么算法教科书使用 "nondecreasing"而不是 "increasing"来提到排序数组?

php - 如何从数组中删除特定键? PHP

c - 随机数组在第一个元素之后给出无效输出 [C]

ruby - 检查 Sinatra/DataMapper 中是否存在记录

ruby-on-rails - 如何在 Rails Webpacker 中添加多个 source_path