N
N
Nikita2016-07-14 16:56:59
Ruby on Rails
Nikita, 2016-07-14 16:56:59

How to sort array data by hash?

Good day!
Please help me sort by hash. There is an array like this:

[{"nr"=>"number", "brand"=>"brand", "name"=>"name", "stock"=>"45", "delivery"=>1, "minq"=>"1", "upd"=>"14.07.16 15:59", "price"=>"992.81", "currency"=>"руб."}, 
{"nr"=>"number", "brand"=>"brand", "name"=>"name", "stock"=>"2", "delivery"=>0, "minq"=>"1", "upd"=>"14.07.16 16:42", "price"=>"1556.64", "currency"=>"руб."}, 
{"nr"=>"number", "brand"=>"brand", "name"=>"name", "stock"=>"5", "delivery"=>1, "minq"=>"1", "upd"=>"14.07.16 15:59", "price"=>"1556.83", "currency"=>"руб."}, 
{"nr"=>"number", "brand"=>"brand", "name"=>"name", "stock"=>"5", "delivery"=>1, "minq"=>"1", "upd"=>"14.07.16 15:59", "price"=>"1658.92", "currency"=>"руб."}]

I need to sort it by "price", now I'm sorting it like this:
for i in 0..array.length - 1
      for j in 0..array.length - i - 2
        if array[j + 1]["price"].to_i < array[j]["price"].to_i
          array[j], array[j + 1] = array[j + 1], array[j]
        end
      end
end

The usual bubble sort, but it seems to me that it is possible to do this in a more rational way.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Grudinkin, 2016-07-14
@niks123123

array_of_hashes.sort_by { |hsh| hsh[:price] }

C
Chronic 86, 2016-07-14
@chronic86

ruby version?
Try like this
array_of_hashes.sort_by(&:price)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question