struct Address {
var name: String
var imageURL: String
var address: String
}
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
let AddressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")]
var filtered = [Address]()
for element in VIPArray {
for address in AddressArray {
if element["name"] == address.name {
filtered.append(address)
}
}
}
for record in filtered {
print(record)
}
OUTPUT:
Address(name: "John B", imageURL: "johnb", address: "178 Main St.")
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av.")
Or:
let filtered: [Address] = AddressArray.filter { (address) -> Bool in
for vip in VIPArray {
if vip["name"] == address.name {
return true
}
}
return false
}
Answer from Dmitry on Stack Overflowstruct Address {
var name: String
var imageURL: String
var address: String
}
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
let AddressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")]
var filtered = [Address]()
for element in VIPArray {
for address in AddressArray {
if element["name"] == address.name {
filtered.append(address)
}
}
}
for record in filtered {
print(record)
}
OUTPUT:
Address(name: "John B", imageURL: "johnb", address: "178 Main St.")
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av.")
Or:
let filtered: [Address] = AddressArray.filter { (address) -> Bool in
for vip in VIPArray {
if vip["name"] == address.name {
return true
}
}
return false
}
let VIPArray = [["name": "John B"], ["name": "Sara K"]]
struct Address {
let name: String
let imageURL: String
let address: String
}
let addressArray = [Address(name: "John B", imageURL: "johnb", address: "178 Main St."),
Address(name: "Dave H", imageURL: "daveh", address: "1011 Victoria St.."),
Address(name: "Sara K", imageURL: "sarak", address: "279 Maple Av."),
Address(name: "Niles K", imageURL: "nilesk", address: "45 King St."),
Address(name: "Ingrid G", imageURL: "ingridg", address: "33 Union St.")]
let myVips = addressArray.filter() {VIPArray.contains(["name":$0.name])}
I have an array of Match objects [Match] with a string property of matchID. I also have an array of strings.
I would like to remove the Match object where matchID equals any string in the array.
I currently have:
var matches = [Match]
var matchIDsToDelete = [String]
for match in matches {
for id in matchIDsToDelete {
if match.matchID == id {
// remove that item from array
}
}
}My concern is removing the object from the array as I'm enumerating. I believe there will be consequences. Any suggestions? I would also love a functional solution as I'm currently reading more about functional programming.
Thanks!
Use Set Operations
Set(toBeFiltered).intersection(Set(theFilter))

Read more: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
let toBeFiltered = ["star0", "star2", "star1", "star0", "star3", "star4"]
let theFilter = ["star1", "star3"]
let filtered = toBeFiltered.filter(theFilter.contains)
One approach is to update your filter to see if any value in pets is in the petArr array:
users = users.filter { $0.pets.contains(where: { petArr.contains($0) }) }
The first $0 is from the filter and it represents each User.
The second $0 is from the first contains and it represents each pet within the pets array of the current User.
If elements inside the internal array are Equatable you can just write:
array1 = array1.filter{ $0.arrayInsideOfArray1 == array2 }
If they are not, you can make them, by adopting Equatable protocol and implementing:
func ==(lhs: YourType, rhs: YourType) -> Bool
Use Set Operations
Set(toBeFiltered).intersection(Set(theFilter))

Read more: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html
let toBeFiltered = ["star0", "star2", "star1", "star0", "star3", "star4"]
let theFilter = ["star1", "star3"]
let filtered = toBeFiltered.filter(theFilter.contains)
Use the filter function
var resultsArray = [String]()
let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]
let filteredArray = array2.filter{ !array1.contains($0) }
resultsArray.appendContentsOf(filteredArray)
If the collections contain unique items consider to use Set rather than Array
Update Swift 5.1:
In iOS 13, macOS 10.15 there is a new API in Array
public func difference<C>(from other: C) -> CollectionDifference<Element> where C : BidirectionalCollection, Self.Element == C.Element
var resultsArray = [String]()
let array1 = ["1","2","2","3","4"]
let array2 = ["1","2","2","3","4","5","6"]
let diff = array2.difference(from: array1)
resultsArray.append(contentsOf: array1)
for change in diff {
switch change {
case .remove(let offset, _, _): resultsArray.remove(at: offset)
case .insert(let offset, let element, _): resultsArray.insert(element, at: offset)
}
}
var resultsArray: [String] = []
let arrayX = ["1","2","2","3","4"]
let arrayY = ["1","2","2","3","4","5","6","7"]
let setX = Set(arrayX), setY = Set(arrayY)
resultsArray.append(contentsOf: setY.subtracting(setX))
This answer is faster than using filter.
If you don't mind the O(n^2), then test directly in one step.
let arrayOne = [["keyphraseId":"tcpid1234", "name":"shakti"], ["keyphraseId":"tcpid456", "name":"shakti"], ["keyphraseId":"tcpid897", "name":"srichandan "], ["keyphraseId":"tcpid779", "name":"prakash"]]
let arrayTwo = [["idstring":"tcpid1234", "name":"shakti"],["idstring":"tcpid456", "name":"shakti"]]
arrayOne.filter { one in
!arrayTwo.contains { two in
one["keyphraseId"] == two["idstring"]
}
}
If you want better performance O(n), drop stringids into a set
let arrayOne = [["keyphraseId":"tcpid1234", "name":"shakti"], ["keyphraseId":"tcpid456", "name":"shakti"], ["keyphraseId":"tcpid897", "name":"srichandan "], ["keyphraseId":"tcpid779", "name":"prakash"]]
let arrayTwo = [["idstring":"tcpid1234", "name":"shakti"],["idstring":"tcpid456", "name":"shakti"]]
let idstrings = Set(arrayTwo.flatMap { $0["idstring"] })
arrayOne.filter {
guard let keyphraseId = $0["keyphraseId"] else { return false }
return !idstrings.contains(keyphraseId)
}
You have 2 arrays as follows:
let arrayOne = [
["keyphraseId":"tcpid1234", "name":"shakti"],
["keyphraseId":"tcpid456", "name":"shakti"],
["keyphraseId":"tcpid897", "name":"srichandan "],
["keyphraseId":"tcpid779", "name":"prakash"]
]
let arrayTwo = [
["idstring":"tcpid1234", "name":"shakti"],
["idstring":"tcpid456", "name":"shakti"]
]
To filter the array you need to follow 2 steps:
List out
idStringsfromarrayTwofilter
arrayOnewith fetchedidStringfrom step 1
To get elements from arrayOne
whose keyphraseId lies in arrayTwo as idstring :
let arrayTwoIds = arrayTwo.map { $0["idstring"] }
let filteredResults = arrayOne.filter { arrayTwoIds.contains($0["keyphraseId"]) }
print(filteredResults)
whose keyphraseId not lies in arrayTwo as idstring :
Just put ! in filter condition:
let filteredResults = arrayOne.filter { !arrayTwoIds.contains($0["keyphraseId"]) }
Hope this will help.
You can do it like this:
let roomTypes = [RoomFilter(roomType: "Twin Room"), RoomFilter(roomType: "Single Room")]
let result = hotels.filter { hotel in
hotel.prices?.contains { price in
roomTypes.contains { rt in
rt.roomType == price.roomType
}
} ?? false
}
In case if a price is a dictionary:
let roomTypes = [RoomFilter(roomType: "Twin Room"), RoomFilter(roomType: "Single Room")]
let result = hotels.filter { hotel in
roomTypes.contains { filterRoomType in
filterRoomType.roomType == hotel.price?.roomType
}
}