How to sort an array of hashes in ruby

ArraysRubySorting

Arrays Problem Overview


I have an array, each of whose elements is a hash with three key/value pairs:

:phone => "2130001111", :zip => "12345", :city => "sometown"

I'd like to sort the data by zip so all the phones in the same area are together. Does Ruby have an easy way to do that? Can will_paginate paginate data in an array?

Arrays Solutions


Solution 1 - Arrays

Simples:

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

Note:

When using sort_by you need to assign the result to a new variable: array_of_hashes = array_of_hashes.sort_by{} otherwise you can use the "bang" method to modify in place: array_of_hashes.sort_by!{}

Solution 2 - Arrays

sorted = dataarray.sort {|a,b| a[:zip] <=> b[:zip]}

Solution 3 - Arrays

Use the bang to modify in place the array:

array_of_hashes.sort_by!(&:zip)

Or re-assign it:

array_of_hashes = array_of_hashes.sort_by(&:zip)

Note that sort_by method will sort by ascending order.

If you need to sort with descending order you could do something like this:

array_of_hashes.sort_by!(&:zip).reverse!

or

array_of_hashes = array_of_hashes.sort_by(&:zip).reverse

Solution 4 - Arrays

If you want to paginate for data in array you should require 'will_paginate/array' in your controller

Solution 5 - Arrays

If you have Nested Hash (Hash inside a hash format) as Array elements (a structure like the following) and want to sort it by key (date here)

data =  [
    {
        "2018-11-13": {
            "avg_score": 4,
            "avg_duration": 29.24
        }
    },
    {
         "2017-03-13": {
            "avg_score": 4,
            "avg_duration": 40.24
        }
    },
    {
         "2018-03-13": {
            "avg_score": 4,
            "avg_duration": 39.24
        }
    }
]

Use Array 'sort_by' method as

data.sort_by { |element| element.keys.first }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjpwView Question on Stackoverflow
Solution 1 - ArraysGarethView Answer on Stackoverflow
Solution 2 - ArraysEduView Answer on Stackoverflow
Solution 3 - ArraysDiego DView Answer on Stackoverflow
Solution 4 - Arraystaivn07View Answer on Stackoverflow
Solution 5 - ArraysAbhiView Answer on Stackoverflow