Ruby - extracting the unique values per key from an array of hashes
Use Array#uniq
:
array_of_hashes = [ {'a' => 1, 'b' => 2 , 'c' => 3} ,
{'a' => 4, 'b' => 5 , 'c' => 3},
{'a' => 6, 'b' => 5 , 'c' => 3} ]
array_of_hashes.map { |h| h['a'] }.uniq # => [1, 4, 6]
array_of_hashes.map { |h| h['b'] }.uniq # => [2, 5]
array_of_hashes.map { |h| h['c'] }.uniq # => [3]
Ruby -- array of hashes, getting unique values
You can combine map
and uniq
:
persons = [
{name: 'Mark', age: 28},
{name: 'John', age: 45},
{name: 'Sam', age: 34},
{name: 'John', age: 34}
]
persons.map { |p| p[:name] }.uniq #=> ["Mark", "John", "Sam"]
Given a hash with an array of values, how to extract numbers of unique values of each key?
Below code would work with more than two keys also
h = {
'a' => ['c', 'b', 'd'],
'b' => ['c', 'b', 'f', 'g']
}
g={}
all_values = h.values.flatten
uniq_elements = all_values.select{|element| all_values.count(element) == 1 }
h.each do |k,v|
g[k] = (v & uniq_elements).count
end
g
If we don't want to check duplicates in self array of hash then we can collect uniq like below
h = { 'cat' => ['c', 'b', 'd', 'c', 'e', 'f'],
'dog' => ['c', 'b', 'f', 'g'],
'pig' => ['h', 'h', 'b', 'f'] }
g={}
all_values = h.values.collect{|val| val.uniq}.flatten
uniq_elements = all_values.select{|element| all_values.count(element) == 1 }
h.each do |k,v|
g[k] = (v & uniq_elements).count
end
g
Unique on an array of hashes based on value
In Ruby 1.9, try the following
a.uniq! {|e| e[:color] }
How do I get the unique elements from an array of hashes in Ruby?
I can get what I want by calling inject
a = [{:a => 1},{:a => 2}, {:a => 1}]
a.inject([]) { |result,h| result << h unless result.include?(h); result }
This will return:
[{:a=>1}, {:a=>2}]
How to get all values for a key from an array of hashes?
I have tested this and it seem to work as expected!
arrOfHashes.map{|i| i["name"]}.sample(1)
How to extract values from hashes into separate arrays?
A simple solution is to iterate the array of hashes and add the required values to two separate arrays:
months = []
counts = []
array_of_hash.each do |hash|
months << hash["month"]
counts << hash["count"]
end
But you could also use each_with_object
months, count = array_of_hash.each_with_object([[], []]) do |hash, accu|
accu[0] << hash["month"]
accu[1] << hash["count"]
end
or iterate twice and get the months and counts separately:
months = array_of_hash.map { |hash| hash["month"] }
counts = array_of_hash.map { |hash| hash["count"] }
Get unique element on basis of string from array of hash
You can pass a block to Array#uniq
in this case:
arr.uniq { |hash| hash[:a] }
How do I efficiently extract all values with a certain key name from a hash of hashes?
Other than optimising the h['email']
part into native extensions, I cannot see how you could make the above example more efficient. The efficiency gain of doing so would be tiny for the example size of data set, and much less than optimising I/O of fetching/parsing this data in the first place I'd suspect.
Depending on your data source, having the hash keys as labels, and not strings, is a common Ruby idiom, and also more efficient in terms of memory use. This is potentially a larger gain in efficiency, and might be worth it provided you don't have to put a large amount of effort in to convert the data (e.g. you can somehow change the nature of the given data structure from your data source, without needing to convert the hash just to query it once!)
How to extract hashes from an array of hashes based on array value
check.flat_map{|c| input_hash.select{|aa| aa["id"] == c}}.map{|a| a["name"]}.join(", ")
=> "george, nancy"
or
input_hash.select{|h| h["name"] if check.include? h["id"]}.map{|aa| aa["name"]}.join(", ")
=> "george, nancy"
Related Topics
Find Number of Bytes a Particular Hash Is Using in Ruby
Using Ruby to Generate Sha512 Crypt-Style Hashes Formatted for /Etc/Shadow
Activerecords Select(:Id).Collect VS. Pluck(:Id) Methods: Why Is Pure Ar "Pluck" Slower
Getaddrinfo Error with Mechanize
Rails 3.2 Activeadmin 'Collection Is Not a Paginated Scope.' Error
How to I Add a Hyperlink to a Cell in Axlsx
Getting Ruby Function Object Itself
Need to Use Add_Index on Migration for Belongs_To/Has_Many Relationship? (Rails 3.2, Active Record)
How to Get the Number of Elements Having Same Attribute in HTML in Watir
What's the Best Background Job Management Library for Rails
Kill Process and Sub-Processes in Ruby on Windows
Rails How to Change Attribute Name When Rendering JSON
How to Render a String as an Erb File
Rvm System-Wide Install Script Url Broken -- What Is Replacement
Ruby: Differencebetween the Comparatives: "||" and "Or"