繁体   English   中英

Ruby - 从散列数组中提取每个键的唯一值

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

从下面的哈希中,需要提取每个键的唯一值

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

需要提取数组中每个键的唯一值

“a”的唯一值应该给出

[1,4,6]

'b'的唯一值应该给出

[2,5]

'c'的唯一值应该给出

[3]

想法?

使用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]

这更通用:

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.

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