我有一个散列数组,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/