birdy
birdy

Reputation: 9636

how to filter an array of hashmaps

I have a hash map of arrays representing colors, shades for each color, and availability of each shade

[
 {"color"=>"red", "shades"=>[]}, 
 {"color"=>"yellow", "shades"=>[]}, 
 {"name"=>"Pink", "shades"=>[{"name"=>"lightpink", "available"=>0}]}, 
 {"name"=>"Green", "shades"=>[{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1},    
    {"name"=>"lightergreen", "available"=>0}]}
}

from this array I want to fetch all the shades with available == 1

so finally i want this:

[ {"name"=>"darkgreen", "available"=>1},
  {"name"=>"lightgreen", "available"=>1}
]

How can I get that?

I tried this but it didn't work:

available_shades = []
all_shades = []
allcolors.each do |color|
  all_shades << color["shades"]
end

available_shades = all_shades.find{|shade| shade["available"] == 1}

Upvotes: 1

Views: 61

Answers (2)

xlembouras
xlembouras

Reputation: 8295

You can use Array#select

array = [
 {"color"=>"red", "shades"=>[]}, 
 {"color"=>"yellow", "shades"=>[]}, 
 {"name"=>"Pink", "shades"=>[{"name"=>"lightpink", "available"=>0}]}, 
 {"name"=>"Green", "shades"=>[{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1},    
    {"name"=>"lightergreen", "available"=>0}]}
]

array.flat_map { |x| x["shades"] }.select { |x| x["available"] == 1 }
#=> [
#=>   {"name"=>"darkgreen", "available"=>1},
#=>   {"name"=>"lightgreen", "available"=>1}
#=> ]

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118261

It can be done as :-

array = [
 {"color"=>"red", "shades"=>[]}, 
 {"color"=>"yellow", "shades"=>[]}, 
 {"name"=>"Pink", "shades"=>[{"name"=>"lightpink", "available"=>0}]}, 
 {"name"=>"Green", "shades"=>[{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1},    
    {"name"=>"lightergreen", "available"=>0}]}
]
ary = array.flat_map do |x| 
  x['shades'].select { |h| h['available'] == 1 } unless x['shades'].empty?
end.compact

ary # => [{"name"=>"darkgreen", "available"=>1}, {"name"=>"lightgreen", "available"=>1}]

Upvotes: 1

Related Questions