Reputation: 55
I have two array of objects that look like this:
MeetingRoomSuggestions
:
init(suggestionReason: String, organizerAvailability: String,
startTime: String, endTime: String, dStart: Date, availability: String,
emailAddress: String, displayName: String, roomEmail: String,
occupancy: Int, building: String)
and Bookings
:
init(startTime: String, endTime: String, dStart: Date, organizer :
String, location : String, subject : String)
I want to be able to filter / exclude MeetingRoomSuggestion
objects from my array if the dStart
property exists in the Bookings
array.
My Code:
let filteredArr = meetingRoomSuggestions.filter { meeting in
return bookingArray!.contains(where: { booking in
return booking.dStart == meeting.dStart
})
}
I also tried filtering on the start string - which is the same in both.
When I print out both the arrays before filtering - you can clearly see there is a booking that exists with the same dStart
. How can I exclude this?
After filtering and printing out using the code:
print("meetings:")
for meeting in self.meetingRoomSuggestions {
print(meeting.roomEmail)
print(meeting.dStart)
print(meeting.startTime)
}
print()
print("bookings:")
for booking in self.bookingArray! {
print(booking.location)
print(booking.dStart!)
print(booking.start)
}
print("filtered array: ", filteredArr)
for items in filteredArr {
print("email: ", items.roomEmail)
print("dstart: ", items.dStart)
}
Returns:
meetings:
[email protected]
2019-02-20 15:00:00 +0000
2019-02-20T15:00:00.0000000
[email protected]
2019-02-20 15:00:00 +0000
2019-02-20T15:00:00.0000000
bookings:
[email protected]
2019-02-20 15:00:00 +0000
2019-02-20T15:00:00.0000000
[email protected]
2019-02-21 10:00:00 +0000
2019-02-21T10:00:00.0000000
[email protected]
2019-02-21 16:00:00 +0000
2019-02-21T16:00:00.0000000
filtered array: [QUBook.MeetingSuggestion, QUBook.MeetingSuggestion]
email: [email protected]
dstart: 2019-02-20 15:00:00 +0000
email: [email protected]
dstart: 2019-02-20 15:00:00 +0000
For some reason, the filtered array is the same as the original meetingRoomSuggestions
array - it doesn't filter out the occurrence of an object with the same dStart
. I suspect the filter is wrong? I have previously been able to filter array of objects by comparing them with array of strings etc but not like this.
Upvotes: 2
Views: 1633
Reputation: 3759
You are using some kind of reverse logic here. What you should be doing is this:
let filteredArr = meetingRoomSuggestions.filter { meeting in
return !bookingArray.contains(where: { booking in
return booking.dStart == meeting.dStart
})
}
In plain english: filter
meetings, leaving those that do not
have their dStart
values equal to the dStart
value of any object in the bookingArray
.
Upvotes: 7