Bliv_Dev
Bliv_Dev

Reputation: 617

Swift filter object array wit another object array

i struggle my had now sine several days with a way to do conditional filter of an object array with another object array.

lack on capabilities to properly abstract here... maybe you ahve some ideas.

I have a given Object Array A but more complex

var ArrA = [{
 number: 1,
 name: "A"
}, {
 number: 2,
 name: "C"
}]

And i want to filer for all results matiching id of Object Array B

var ArrB = [{
 id: 1,
 categorie: "wine"
}, {
 id: 3,
 categorie: "beer"
}, {
 id: 10,
 categorie: "juice"
}]

And in the best case moving this directly also together with an if condition.... but i was not able to handle it ... here is where i am now ... which is not working....

let newArray = ArrA.filter{$0.number == ArrB.... }.
if (newArray.count != 0){
    // Do something
}

is there a lean way to compare one attribute of every object in an array with one attribute of another every object in an array ?

Upvotes: 0

Views: 97

Answers (1)

Crocobag
Crocobag

Reputation: 2340

Lets break this down: You need all arrA objects that matches arrB ids, so first thing first you need to map your arrB to a list of id (because you dont need the other infos)

let arrBid = Set(arrB.map({ $0.id })) // [1, 3, 10]

As commented below, casting it to Set will give you better results for huge arrays but is not mandatory though

Then you just need to filter your first arrA by only keeping object that id is contained into arrBid :

let arrAFilter = arrA.filter({ arrBid.contains($0.number) })

[(number: 1, name: "A")]

and voila

Upvotes: 1

Related Questions