如何通过自定义排序顺序对数组排序?

时间:2021-08-02 19:43:30

I have an array of hashes:

我有一组散列:

[{number: 1},{number: 2}, {number: 3}, {number: 4}]

I need to sort them based on a custom order:

我需要根据定制的顺序对它们进行排序:

[3,4,1,2]

Thus, the result should be:

因此,结果应该是:

[{number: 3},{number: 4}, {number: 1}, {number: 2}]

I know sort_by exists but I've only used it for ascending and descending orders.

我知道sort_by存在,但我只对升序和降序使用它。

I could go crazy and not worry about performance, but is there an efficient way to order this array of hashes based on a custom order via an array?

我可能会发疯,不担心性能,但是否有一种有效的方法,可以根据一个数组的自定义顺序排列这些散列?

3 个解决方案

#1


5  

Depending on how one interprets the problem, a potential solution might be:

根据人们如何解释这个问题,一个潜在的解决方案可能是:

input  = [{number: 6},{number: 10}, {number: 2}, {number: 8}]
hash   = Hash[input.map { |h| [h[:number], h] }]
order  = [8,10,6,2]
output = hash.values_at(*order)
# => [{:number=>8}, {:number=>10}, {:number=>6}, {:number=>2}]

#2


1  

Just sort on the index of the value in a

只是对a的值进行排序。

h = [{number: 1},{number: 2}, {number: 3}, {number: 4}]
a = [3,4,1,2]

p h.sort_by{|el| a.index(el[:number])}
# => [{:number=>3}, {:number=>4}, {:number=>1}, {:number=>2}]

#3


1  

input  = [{number: 6},{number: 10}, {number: 2}, {number: 8}] 
order  = [8,10,6,2]
order.map{|i| input.find{|h| h[:number] == i }}
# => [{:number=>8}, {:number=>10}, {:number=>6}, {:number=>2}]

Updated shorter code:

更新短代码:

input  = [{number: 6},{number: 10}, {number: 2}, {number: 8}] 
order  = [8,10,6,2]
input.group_by{|h| h[:number]}
# => {6=>[{:number=>6}],
#     10=>[{:number=>10}],
#     2=>[{:number=>2}],
#     8=>[{:number=>8}]}
input.group_by{|h| h[:number]}.values_at(*order)
# => [[{:number=>8}], [{:number=>10}], [{:number=>6}], [{:number=>2}]]

#1


5  

Depending on how one interprets the problem, a potential solution might be:

根据人们如何解释这个问题,一个潜在的解决方案可能是:

input  = [{number: 6},{number: 10}, {number: 2}, {number: 8}]
hash   = Hash[input.map { |h| [h[:number], h] }]
order  = [8,10,6,2]
output = hash.values_at(*order)
# => [{:number=>8}, {:number=>10}, {:number=>6}, {:number=>2}]

#2


1  

Just sort on the index of the value in a

只是对a的值进行排序。

h = [{number: 1},{number: 2}, {number: 3}, {number: 4}]
a = [3,4,1,2]

p h.sort_by{|el| a.index(el[:number])}
# => [{:number=>3}, {:number=>4}, {:number=>1}, {:number=>2}]

#3


1  

input  = [{number: 6},{number: 10}, {number: 2}, {number: 8}] 
order  = [8,10,6,2]
order.map{|i| input.find{|h| h[:number] == i }}
# => [{:number=>8}, {:number=>10}, {:number=>6}, {:number=>2}]

Updated shorter code:

更新短代码:

input  = [{number: 6},{number: 10}, {number: 2}, {number: 8}] 
order  = [8,10,6,2]
input.group_by{|h| h[:number]}
# => {6=>[{:number=>6}],
#     10=>[{:number=>10}],
#     2=>[{:number=>2}],
#     8=>[{:number=>8}]}
input.group_by{|h| h[:number]}.values_at(*order)
# => [[{:number=>8}], [{:number=>10}], [{:number=>6}], [{:number=>2}]]