Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Filter other arrays based on another Bool array

I have an array of Bools and want to edit an array of Scores and an array of Dates for the values that are False. I can't get to it. I thought of getting elements that are false and using that array to remove those elements from the score array but I can imagine there is a direct way of doing it.

let hbiCompleteArray = [true, true, true, true, false, true, true, false, false]

let hbiScoreArray = [12, 12, 12, 12, 3, 13, 13, 2, 2]

I want an array of completeHbiScores = [12, 12, 12, 12, 13, 13]

like image 324
SashaZ Avatar asked Dec 14 '22 03:12

SashaZ


1 Answers

If you have to use two arrays, you can solve this with zip, filter and map like this:

let hbiCompleteArray = [true, true, true, true, false, true, true, false, false]
let hbiScoreArray = [12, 12, 12, 12, 3, 13, 13, 2, 2]

let result = zip(hbiCompleteArray, hbiScoreArray).filter { $0.0 }.map { $1 }
print(result)

Gives:

[12, 12, 12, 12, 13, 13]

Explanation: the zip interleaves the two arrays (makes an array of (Bool, Int) tuples), then filter { $0.0 } only keeps the true booleans, then the map only keeps the Int values.

like image 113
Eric Aya Avatar answered Jan 15 '23 11:01

Eric Aya