Search code examples
ruby-on-railsrubyruby-hash

Filtering out hashes from arrays of hashes that have matching keys


Say I have an array of hashes like so

default_search_order = [
    { field: 'subscribers.nickname',   direction: 'ASC' },
    { field: 'subscribers.email',      direction: 'ASC' },
    { field: 'roles.name',             direction: 'ASC' },
    { field: 'subscribers.first_name', direction: 'ASC' }
]

and I have another array of hashes provided by a query like this:

order = [
    { :field => "subscribers.nickname",  :direction => "DESC"},
    { :field => "subscribers.email",     :direction => "DESC"},
    { :field => "subscribers.last_name", :direction => "DESC"}
]

I want to filter out hashes from default_search_order that have matching values for field and then combine the two arrays of hashes into one array of hashes like so.

correct = [
    { field: "subscribers.nickname",   direction: "DESC"},
    { field: "subscribers.email",      direction: "DESC"},
    { field: "subscribers.last_name",  direction: "DESC"},
    { field: "roles.name",             direction: "ASC" },
    { field: "subscribers.first_name", direction: "ASC" }
]

How would I do that in Ruby on Rails? I've been trying #.delete_if? and #.keep_if? and #.select but I'm going in circles. Help?


Solution

  • Another solution would be to merge both Arrays and extract unique values

    correct = (order + default_search_order).uniq { |f| f[:field] }
    
    correct = order.push(*default_search_order).uniq { |f| f[:field] }
    

    Note: Here variable order matters while merging arrays if default_search_order is written before order variable then result would be different.