0

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 ?

1
  • This is called the "intersection" of two arrays, btw. Commented Sep 26, 2019 at 0:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Use a Set for faster contains: let arrBid = Set(arrB.map { $0.id }). contains is O(n) for an Array and O(1) for a Set.
You don't need the return inside the map and filter closures.
@vacawama I know, you do not need them if there is only a single line in the closure, I find it clearer though but it may not be the case for everyone
Hey that is great.. it works like a charm ! Thank you... i really was struggeling how to get a single attribute array from my objects :) ... any chance i can combine the filter with the if statement as well ?
@Bliv_Dev you could do let arrAFilter = arrA.filter({ Set(arrB.map({ $0.id })).contains($0.number) }) but I suggest you do NOT. the reason is that the closure you put inside filter() will be triggered for each element, therefore it will compute the map for each element in arrA, which is not optimal at all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.