Remove duplicates from array comparing the properties of its objects

前端 未结 6 1365
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 03:50

Suppose I have a class Event, and it has 2 properties: action (NSString) and date (NSDate).

And suppose I have an array of Event objects. The problem is that \"date\" pr

6条回答
  •  萌比男神i
    2021-02-04 04:01

    Here is working Swift code snipped which does remove duplicates while keeping the order of elements.

    // Custom Struct. Can be also class. 
    // Need to be `equitable` in order to use `contains` method below
    struct CustomStruct : Equatable {
          let name: String
          let lastName : String
        }
    
    // conform to Equatable protocol. feel free to change the logic of "equality"
    func ==(lhs: CustomStruct, rhs: CustomStruct) -> Bool {
      return (lhs.name == rhs.name && lhs.lastName == rhs.lastName)
    }
    
    let categories = [CustomStruct(name: "name1", lastName: "lastName1"),
                      CustomStruct(name: "name2", lastName: "lastName1"),
                      CustomStruct(name: "name1", lastName: "lastName1")]
    print(categories.count) // prints 3
    
    // remove duplicates (and keep initial order of elements)
    let uniq1 : [CustomStruct] = categories.reduce([]) { $0.contains($1) ? $0 : $0 + [$1] }
    print(uniq1.count) // prints 2 - third element has removed
    

    And just if you are wondering how this reduce magic works - here is exactly the same, but using more expanded reduce syntax

    let uniq2 : [CustomStruct] = categories.reduce([]) { (result, category) in
      var newResult = result
      if (newResult.contains(category)) {}
      else {
        newResult.append(category)
      }
      return newResult
    }
    uniq2.count // prints 2 - third element has removed
    

    You can simply copy-paste this code into a Swift Playground and play around.

提交回复
热议问题