Reputation: 190
Anyone know an elegant way to return an array of index values from an array of Bools where the values are true. E.g:
let boolArray = [true, true, false, true]
This should return:
[0,1,3]
Upvotes: 5
Views: 1656
Reputation: 73206
let boolArray = [true, true, false, true]
let trueIdxs = boolArray.enumerate().flatMap { $1 ? $0 : nil }
print(trueIdxs) // [0, 1, 3]
Alternatively (possibly more readable)
let boolArray = [true, true, false, true]
let trueIdxs = boolArray.enumerate().filter { $1 }.map { $0.0 }
print(trueIdxs) // [0, 1, 3]
Upvotes: 8