ruby : How to sort an array of hash in a given order of a particular key

标签 ruby arrays sorting hash

我有一个散列数组,id 是散列中的键之一。我想根据 ID 值的给定顺序对数组元素进行排序。

假设我的数组(size=5)是:

[{"id"=>1. ...}, {"id"=>4. ...}, {"id"=>9. ...}, {"id"=>2. ...}, {"id"=>7. ...}]

我想对数组元素进行排序,使其 id 的顺序如下:

[1,3,5,7,9,2,4,6,8,10]

所以预期的结果是:

[{'id' => 1},{'id' => 7},{'id' => 9},{'id' => 2},{'id' => 4}]

最佳答案

这里是任何自定义索引的解决方案:

def my_index x 
  # Custom code can be added here to handle items not in the index.
  # Currently an error will be raised if item is not part of the index.
  [1,3,5,7,9,2,4,6,8,10].index(x) 
end

my_collection = [{"id"=>1}, {"id"=>4}, {"id"=>9}, {"id"=>2}, {"id"=>7}]
p my_collection.sort_by{|x| my_index x['id'] } #=> [{"id"=>1}, {"id"=>7}, {"id"=>9}, {"id"=>2}, {"id"=>4}]

然后你可以按照你想要的任何方式格式化它,也许这样更漂亮:

my_index = [1,3,5,7,9,2,4,6,8,10]
my_collection.sort_by{|x| my_index.index x['id'] }

关于 ruby : How to sort an array of hash in a given order of a particular key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21673089/

相关文章:

ruby-on-rails - 在 Ruby on Rails 中,如何使全局常量在开发模式下自动加载,而无需重新启动服务器?

ruby-on-rails - Rails 在搜索中组合多个列

javascript - 合并来自两个数组的值

java - Arrays.sort 列表<E>

java - 如何对两个数组进行相互关联的排序?

javascript - array.push() 不起作用,即使数组对象已明确定义并在范围内

ruby-on-rails - delayed_job 的 exception_notification

ruby - ruby 集合/可枚举的炫酷技巧和富有表现力的片段

arrays - 当有集合时,为什么在 VBA 中使用数组?

c - 使用 2 函数进行冒泡排序