[英]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 “a”的唯一值应该给出
[1,4,6]
unique values for 'b' should give 'b'的唯一值应该给出
[2,5]
unique values for 'c' should give 'c'的唯一值应该给出
[3]
Thoughts ? 想法?
Use Array#uniq
: 使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.