【问题标题】:Filter Array based on the Filtering of Another Array Swift基于另一个数组Swift的过滤过滤数组
【发布时间】:2015-07-07 05:16:18
【问题描述】:

假设我有两个数组:

var arrayA = ["Yes", "Yes2", "Not Answered", "No"]
var arrayB = ["Yes", "NA", "Yes2", "NA"]

我想通过执行以下操作从 arrayB 中删除“NA”:

var filtered = arrayB.filter({$0 != "NA"})

如何删除在 arrayA 中删除的相同索引处的项目。我考虑过使用 find() 函数,但它只返回字符串出现的第一个索引。您可以通过以下方式从数组中删除重叠:

let res = arrayA.filter { !contains(arrayB, $0) }

但是如何根据另一个数组的过滤来过滤一个数组呢?

结果应该是:

arrayBFiltered = ["Yes", "Yes2"]
arrayAFiltered = ["Yes", "Not Answered"]

有什么想法吗?

【问题讨论】:

  • 您已经接受了我认为最不“迅速”的方式和最骇人听闻的方式的答案。 @Matteo 的方法更好,也更“迅速”。我确实想知道为什么您没有数据模型来保存这些数据?如果它们密切相关,那么您应该将它们放在一个模型中。

标签: ios arrays swift


【解决方案1】:

您可能更喜欢使用zip

var arrayA = ["Yes", "Yes2", "Not Answered", "No"]
var arrayB = ["Yes", "NA", "Yes2", "NA"]

let result = filter(zip(arrayA, arrayB)) { (a, b) in b != "NA" }

for (a, b) in result {
    println("A: \(a) -> B: \(b)")
}

编辑:SWIFT 2.0

在 Swift 2.0 中,为了更清晰的后续代码,获取一个合并的 ad-hod struct(比如...Foo)的数组将更加容易:

struct Foo {
    let a: String
    let b: String
}
// Foo.init will be the function automatically generated by the default initialiser

let result = zip(arrayA, arrayB)
    .filter { (a, b) in b != "NA" }
    .map(Foo.init)
// Order of a and b is important

// result is an Array<Foo> suitable for a clearer subsequent code
for item in result {
    print("A: \(item.a) -> B: \(item.b)")
}

希望对你有帮助

【讨论】:

  • 这是我回来写的。这是执行此操作的“快速”方式。虽然,我质疑为什么 OP 没有创建一个对象来保存这些相关数据?
  • @Fogmeister 作为练习,我添加了一个 Swift 2.0 变体 ;-)
【解决方案2】:

How can I sort multiple arrays based on the sorted order of another array 的想法可以 在这里使用,这将适用于两个或多个数组:

let arrayA = ["Yes", "Yes2", "Not Answered", "No"]
let arrayB = ["Yes", "NA", "Yes2", "NA"]

// Determine array indices that should be kept:
let indices = map(filter(enumerate(arrayB), { $1 != "NA" } ), { $0.0 } )

// Filter arrays based on the indices:
let arrayAFiltered = Array(PermutationGenerator(elements: arrayA, indices: indices))
let arrayBFiltered = Array(PermutationGenerator(elements: arrayB, indices: indices))

println(arrayAFiltered) // [Yes, Not Answered]
println(arrayBFiltered) // [Yes, Yes2]

【讨论】:

    【解决方案3】:

    另一种解决方案是直接在 filter 闭包内制作删除代码:

    // both are vars so you can mutate them directly
    var arrayA = ["Yes", "Yes2", "Not Answered", "No"]
    var arrayB = ["Yes", "NA", "Yes2", "NA"]
    
    arrayA = filter(enumerate(arrayA)){
        arrayB.removeAtIndex($0)
        return $1 != "Na"
    }
    
    // use filtered arrayA and arrayB
    

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2013-02-12
      相关资源
      最近更新 更多