简体   繁体   中英

Ruby - extracting the unique values per key from an array of hashes

From a hash like the below one, need to extract the unique values per key

array_of_hashes = [ {'a' => 1, 'b' => 2 , 'c' => 3} , 
                    {'a' => 4, 'b' => 5 , 'c' => 3}, 
                    {'a' => 6, 'b' => 5 , 'c' => 3} ]

Need to extract the unique values per key in an array

unique values for 'a' should give

[1,4,6]

unique values for 'b' should give

[2,5]

unique values for 'c' should give

[3]

Thoughts ?

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]

This is more generic:

options = {}
distinct_keys = array_of_hashes.map(&:keys).flatten.uniq
distinct_keys.each do |k|
  options[k] = array_of_hashes.map {|o| o[k]}.uniq
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM