v0lk
v0lk

Reputation: 58

How to initialise array of dictionary keys based on the values of the dictionary keys

How can I initialise an array of filtered keys based on the values for the keys?

In this case I want to return all the elements that are 'true' which are: ["red", "green"]

var selectedColors = [
    "blue":   false,
    "red":    true,
    "yellow": false,
    "green":  true,
    "black":  false,
]

so basically I want to achieve this:

//PSUEDO CODE
var trueColors = selectedColours.selectKeysWhereValIsTrue()

Upvotes: 1

Views: 63

Answers (4)

Alexander
Alexander

Reputation: 63271

Although .filter { $1 }.keys is more readable (and probably a better go-to), it's worth noting that you can do both operations in one using compactMap, which might get you some performance gains if you have big data sets:

let trueColors = selectedColors.compactMap { color, bool in
    bool ? color : nil
}

Upvotes: 2

Mashood Murtaza
Mashood Murtaza

Reputation: 487

let trueColors = selectedColors.filter({ $0.value }).keys

Upvotes: 1

Nakwenda
Nakwenda

Reputation: 230

selectedColors.filter{ $1 }.map{ $0.key }

Upvotes: 4

Shehata Gamal
Shehata Gamal

Reputation: 100523

Do

let res = Array(selectedColors.filter { $0.value }.keys) // ["red", "green"]

Upvotes: 1

Related Questions