Home > OS >  Filter array to keep only if object value is true
Filter array to keep only if object value is true

Time:05-29

I am building an Rails 5.2 app. In this app I let my users save their settings.

I got an array that looks like this:

[{"email"=>true}, {"alert"=>true}, {"push"=>false}]

The desired outcome for the above array is below. I want to only keep the object/value in the array if the value is true. If it is false it should not show up in the new array.

["email", "alert"]

CodePudding user response:

Assuming you have this array

settings = [{"email"=>true}, {"alert"=>true}, {"push"=>false}]

You need the following

settings.map { |item| item.keys.first if item.values.first == true }.compact
=> ["email", "alert"]

CodePudding user response:

arr = [{"email"=>true}, {"alert"=>true}, {"push"=>false}]
arr.filter_map do |h|
  k, v = h.flatten
  k if v
end
  #=> ["email", "alert"]

See Enumerable#filter_map and Hash#flatten.


If

h = {"email"=>true}

then

k, v = h.flatten
  #=> ["email", true]
k #=> "email"
v #=> true

Since v #=> true k is appended to the array that is returned by filter_map.

  • Related