Home:ALL Converter>Filter Array based on the Filtering of Another Array Swift

Filter Array based on the Filtering of Another Array Swift

Ask Time:2015-07-07T13:16:18         Author:modesitt

Json Formatter

Say I had two arrays:

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

And I wanted to remove the "NA"s from arrayB by doing:

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

How could I remove the items at the same indexes removed in arrayA. I thought about using the find() function, but that only returns the first index a string appears. You can remove overlap from the arrays by:

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

but how could I filter an array based on the filtering of another array?

the result would have:

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

Any ideas?

Author:modesitt,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/31260249/filter-array-based-on-the-filtering-of-another-array-swift
Matteo Piombo :

You might prefer using zip:\n\nvar arrayA = [\"Yes\", \"Yes2\", \"Not Answered\", \"No\"]\nvar arrayB = [\"Yes\", \"NA\", \"Yes2\", \"NA\"]\n\nlet result = filter(zip(arrayA, arrayB)) { (a, b) in b != \"NA\" }\n\nfor (a, b) in result {\n println(\"A: \\(a) -> B: \\(b)\")\n}\n\n\nEDIT: SWIFT 2.0\n\nIn Swift 2.0 it will be even easier to obtain an array of a consolidated ad-hod struct (say ... Foo) for clearer subsequent code:\n\nstruct Foo {\n let a: String\n let b: String\n}\n// Foo.init will be the function automatically generated by the default initialiser\n\nlet result = zip(arrayA, arrayB)\n .filter { (a, b) in b != \"NA\" }\n .map(Foo.init)\n// Order of a and b is important\n\n// result is an Array<Foo> suitable for a clearer subsequent code\nfor item in result {\n print(\"A: \\(item.a) -> B: \\(item.b)\")\n}\n\n\nHope this helps",
2015-07-07T05:28:05
Martin R :

The ideas from How can I sort multiple arrays based on the sorted order of another array could\nbe used here, that would work for two or more arrays:\n\nlet arrayA = [\"Yes\", \"Yes2\", \"Not Answered\", \"No\"]\nlet arrayB = [\"Yes\", \"NA\", \"Yes2\", \"NA\"]\n\n// Determine array indices that should be kept:\nlet indices = map(filter(enumerate(arrayB), { $1 != \"NA\" } ), { $0.0 } )\n\n// Filter arrays based on the indices:\nlet arrayAFiltered = Array(PermutationGenerator(elements: arrayA, indices: indices))\nlet arrayBFiltered = Array(PermutationGenerator(elements: arrayB, indices: indices))\n\nprintln(arrayAFiltered) // [Yes, Not Answered]\nprintln(arrayBFiltered) // [Yes, Yes2]\n",
2015-07-07T05:39:38
yy