Munish Prabhu
Munish Prabhu

Reputation: 15

Sort Array of Hashes Keys

I am looking for a solution to sort the Hash keys in an Array.

arr = [{"name"=>"Product Management", "id"=>647628}, {"name"=>"Sales", "id"=>647630}]

arr.each {|inner_hash| inner_hash.sort}

Expected Result:

[{"id"=>647628, "name"=>"Product Management"}, {"id"=>647630, "name"=>"Sales"}]

Upvotes: 0

Views: 65

Answers (2)

uday
uday

Reputation: 1481

you can use ruby Hash#sort_by to sort the elements of a Hash:

arr.map { |inner_hash| inner_hash.sort_by(&:first).to_h }
>> [{"id"=>647628, "name"=>"Product Management"}, {"id"=>647630, "name"=>"Sales"}]

Upvotes: 2

mechnicov
mechnicov

Reputation: 15437

Basically you don't need to sort hashes, but you can

arr.map { |h| h.sort.to_h }

# => [{"id"=>647628, "name"=>"Product Management"}, {"id"=>647630, "name"=>"Sales"}]

Upvotes: 2

Related Questions