Danny
Danny

Reputation: 190

Return an array of index values from array of Bool where true

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

Answers (1)

dfrib
dfrib

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

Related Questions