Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort an array of hashes by a value in the hash?

People also ask

Can we sort an array using hashing?

Explanation of sorting using hashing if the array has negative and positive numbers: Step 1: Create two hash arrays, one for positive and the other for negative. Step 2: the positive hash array will have a size of max and the negative array will have a size of min.

How do you sort an array of hashes in Ruby?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)

How do you sort values in an array?

PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.


Ruby's sort doesn't sort in-place. (Do you have a Python background, perhaps?)

Ruby has sort! for in-place sorting, but there's no in-place variant for sort_by in Ruby 1.8. In practice, you can do:

sorted = sort_me.sort_by { |k| k["value"] }
puts sorted

As of Ruby 1.9+, .sort_by! is available for in-place sorting:

sort_me.sort_by! { |k| k["value"]}

As per @shteef but implemented with the sort! variant as suggested:

sort_me.sort! { |x, y| x["value"] <=> y["value"] }

Although Ruby doesn't have a sort_by in-place variant, you can do:

sort_me = sort_me.sort_by { |k| k["value"] }

Array.sort_by! was added in 1.9.2


You can use sort_me.sort_by!{ |k| k["value"]}. This should work.