Home > database >  Filter array by matching id properties
Filter array by matching id properties

Time:12-06

I feel like this has to be answered some where, but I have been searching for a few days with no luck. I have an example below. I have an array of users and I need to filter them down to the ones that have a matching ID property, I know the code below doesn't compile.. would be very grateful for any help with this.

    struct User {
    var id: Int
    var name: String
}

let userArray = [
    User(id: 1, name: "A"),
    User(id: 2, name: "B"),
    User(id: 1, name: "C"),
    User(id: 3, name: "D"),
]


let newArray = userArray.filter({ $0.id == $1.id })


//  This is what i want to achieve 
// newArray = [User(id: 1, name: "A"),  User(id: 1, name: "C")]

In the actual project, the id is dynamically returned. So I just need to be able to check for what is matching, without knowing what the id will actually be.

CodePudding user response:

Your condition in filter does not compare to a given id value. Below is one added called, which I call matchingId:

struct User {
  var id: Int
  var name: String
}

let userArray = [
  User(id: 1, name: "A"),
  User(id: 2, name: "B"),
  User(id: 1, name: "C"),
  User(id: 3, name: "D"),
]

let matchingId = 1   // or: let matchingId = someFunctionCallReturningAnId()

let result = userArray.filter { $0.id == matchingId }

print(result)

CodePudding user response:

Your approach won't work as filter only takes one dynamic parameter and only processes one item at a time. Therefore it can't match two separate array entries.

You example also doesn't specify how you want to handle the situation where you have multiples of different User.id. This answer assumes you want to be able to separate them into separate arrays.

Dictionary has a handy initialiser that will do the bulk of the work for you and group on a defined property. Grouping on id will give you a dictionary where the key is the id and the values an array of matching User records. You can then filter the dictionary to get a dictionary where there are multiple users for any id.

let multiples = Dictionary(grouping: userArray, by: \.id).filter{$0.value.count > 1}

Using you data you will end up with a dictionary of:

[1: [User(id: 1, name: "A"), User(id: 1, name: "C")] ]
  • Related