简体   繁体   English

通过匹配另一个数组中元素的属性从数组中删除元素

[英]Remove elements from an array by matching a property of elements in another array

I have two arrays: 我有两个数组:

var sessionsToDisplay : [SessionData]
var sessionsToDisplayTemp : [SessionData]

The SessionData class has a startTime Property. SessionData类具有startTime属性。 So, if the first sessionToDisplay array contains these items: 因此,如果第一个sessionToDisplay数组包含以下各项:

SessionData(startTime: "08:00", ...),
SessionData(startTime: "10:30", ...),
SessionData(startTime: "13:30", ...),
SessionData(startTime: "16:00", ...),

and the sessionsToDisplayTemp contains these: sessionsToDisplayTemp包含以下内容:

SessionData(startTime: "06:30", ...),
SessionData(startTime: "16:00", ...),
SessionData(startTime: "12:30", ...),
SessionData(startTime: "15:30", ...),
SessionData(startTime: "08:00", ...),

I have to remove elements from sessionsToDisplayTemp , whose startTime is already there in the first array. 我必须删除从元件sessionsToDisplayTemp ,其startTime已经存在所述第一阵列英寸 So the result should be an array that has these elements: 因此,结果应该是包含以下元素的数组:

SessionData(startTime: "06:30", ...),
SessionData(startTime: "12:30", ...),
SessionData(startTime: "15:30", ...),
SessionData(startTime: "08:00", ...),

You can use filter to check that an object isn't in the other array 您可以使用filter检查对象是否不在另一个数组中

let out = sessionsToDisplayTemp.filter {data in
    !sessionsToDisplay.contains {$0.startTime == data.startTime}
}

or if you want to remove them directly 或者如果您想直接删除它们

sessionsToDisplayTemp.removeAll { data in
    sessionsToDisplay.contains {data.startTime == $0.startTime}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM