我有一个数组数组:
x = [ [“ready”,5],[“shipping”,1],[“pending”,1],[“refunded”,1], [“已交付”,23],[“已安排”,1],[“已取消”,51]]我的排序数组是
order_array = [ ” …
你可以尝试下面的代码来有效地找到输出,
order_array.map { |p| x.detect { |y| y[0] == p } }.compact # => [["ready", 5], ["shipped", 1], ["scheduled", 1], ["delivered", 23], ["canceled", 51], ["refunded", 1]]
我假设:
x
order_array
sorted_array
x = [ ["ready", 5], ["shipped", 1], ["pending", 1], ["refunded", 1], ["originated", 3], ["delivered", 23], ["scheduled", 1], ["ready", 8], ["canceled", 51] ] order_array = [ "ready", "in_progress", "received", "shipped", "scheduled", "pick_up", "delivered", "canceled", "failed", "refunded", "refund_failed" ]
order_pos = order_array.each_with_object({}) { |word,h| h[word] = [] } #=> {"ready"=>[], "in_progress"=>[], "received"=>[], "shipped"=>[], # "scheduled"=>[], "pick_up"=>[], "delivered"=>[], "canceled"=>[], # "failed"=>[], "refunded"=>[], "refund_failed"=>[]} back = x.each_with_index.with_object([]) { |((word,v),i),back| order_pos.key?(word) ? (order_pos[word] << i) : back << [word,v] } #=> [["pending", 1], ["originated", 3]] order_pos.flat_map { |word,offsets| offsets.map { |i| x[i] } }.concat(back) #=> [["ready", 5], ["ready", 8], ["shipped", 1], ["scheduled", 1], # ["delivered", 23], ["canceled", 51], ["refunded", 1], ["pending", 1], # ["originated", 3]]
注意:
order_pos #=> {"ready"=>[0, 7], "in_progress"=>[], "received"=>[], "shipped"=>[1], # "scheduled"=>[6], "pick_up"==>[], "delivered"=>[5], "canceled"=>[8], # "failed"=>[], "refunded"=>[3], "refund_failed"=>[]}
有必要初始化 order_pos 为了按键排序 order_arr 。这是Ruby 1.9中有争议的变化的一个例子,它保证了散列键将保持按键插入顺序。
order_pos
order_arr
ASSOC 似乎很有帮助:“搜索一个数组,其元素也是使用obj。==将obj与每个包含数组的第一个元素进行比较的数组。”
order_array.map{|e| x.assoc(e) }.compact