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

前端 未结 2 1395
深忆病人
深忆病人 2020-12-31 18:32

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

array_of_hashes = [ {\'a\' => 1, \'b\' => 2 , \'c\' => 3} , 
                      


        
2条回答
  •  执念已碎
    2020-12-31 19:02

    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]
    

提交回复
热议问题