Home > Mobile >  Re-order array of array of hash in ruby based on an array of key values
Re-order array of array of hash in ruby based on an array of key values

Time:09-16

I have an array of array of hash. For example,

arr =[[{:id=>61,:price=>20}, {:id=>61, :price=>23}, {:id=>61, :price=>60}],
     [{:id=>65, :price=>20}, {:id=>65, :price=>23}, {:id=>65, :price=>60}],
     [{:id=>69, :price=>20}, {:id=>69, :price=>33}, {:id=>69, :price=>80}]]

order_arr = [65,69,61]

How can I reorder the above array in a given order(based on 'order_arr') of key :id .

So, the result should be as below:

[[{:id=> 65, :price=>20}, {:id=>65, :price=>23}, {:id=>65, :price=>60}],
  [{:id=>69, :price=>20}, {:id=>69, :price=>33}, {:id=>69, :price=>80}],
  [{:id=>61,:price=>20}, {:id=>61, :price=>23}, {:id=>61, :price=>60}]]

Please help

CodePudding user response:

I use the indices of your order_arr to sort the array of arrays with sort_by

arr =[[{:id=>61,:price=>20}, {:id=>61, :price=>23}, {:id=>61, :price=>60}],
     [{:id=>65, :price=>20}, {:id=>65, :price=>23}, {:id=>65, :price=>60}],
     [{:id=>69, :price=>20}, {:id=>69, :price=>33}, {:id=>69, :price=>80}]]


order_arr = [65,69,61]
sorted_arr = arr.sort_by { |ary| order_arr.index(ary.first[:id]) }

pp sorted_arr
  • Related