说我有两个阵列:
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"]
有什么想法吗?
答案 0 :(得分:5)
您可能更喜欢使用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中,获取一个合并后的广告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)")
}
希望这有帮助
答案 1 :(得分:1)
来自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]
答案 2 :(得分:0)
另一种解决方案是直接在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