Swift Filter other arrays based on another Bool array

I have an array of Bools and you want to edit the Scores array and the Dates array for False values. I can’t get to him. I was thinking about getting elements that are false and using this array to remove these elements from the points array, but I can imagine that there is a direct way to do this.

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

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

I need an array completeHbiScores = [12, 12, 12, 12, 13, 13]

+4
source share
4 answers

If you need to use two arrays, you can solve this with zip, filterand mapas follows:

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]

: zip ( (Bool, Int)), filter { $0.0 } true booleans, map Int.

+5

. , . , :

struct Score {
    let isComplete: Bool
    let finalScore: Int
}

, . :

let scores = [
    Score(isComplete: true, finalScore: 12),
    Score(isComplete: true, finalScore: 12),
    Score(isComplete: true, finalScore: 12),
    Score(isComplete: true, finalScore: 12),
    Score(isComplete: false, finalScore: 3),
    Score(isComplete: true, finalScore: 13),
    Score(isComplete: true, finalScore: 13),
    Score(isComplete: false, finalScore: 2),
    Score(isComplete: false, finalScore: 2),
]

,

let completeScores = scores.filter { $0.isComplete }

, , :

let finalCompleteScores = completeScores.map { $0.finalScore }

, , .

+4

, - , , Eric, :

let completeHbiScores = zip(hbiCompleteArray, hbiScoreArray).reduce([Int]()){
    (newArray,zippedArray) in
    if zippedArray.0 {
        return newArray + [zippedArray.1]
    }
    else {
        return newArray
    }}
+1
source

Another fairly simple way to do this, which is repeated only once through your arrays, is this:

let hbiCompleteArray = [true, true, true, true, false, true, true, false, false]
let hbiScoreArray = [12, 12, 12, 12, 3, 13, 13, 2, 2]
var completeHbiScores = [Int]()

for score in hbiScoreArray.enumerated() {
  // break out of the loop if we're at the end of hbiCompleteArray
  // assuming that no value means default to false
  guard score.offset < hbiCompleteArray.count else { break }

  // go to the next score if the current element is false
  guard hbiCompleteArray[score.offset] else { continue }

  completeHbiScores.append(score.element)
}
0
source

Source: https://habr.com/ru/post/1656230/


All Articles