Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 323
Danny Avatar asked Jul 06 '16 13:07

Danny


1 Answers

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]
like image 105
dfrib Avatar answered Oct 01 '22 18:10

dfrib