JLanders
JLanders

Reputation: 101

Remove duplicated in a Struct Array

I am filtering an array that can have a value where there are multiple Models of the same name, only they have different model numbers.

Variables

var modelArray = [model]()

Struct

struct model {
    var modelName = String();
    var modelNumber = String();
    var manufacturer = String();
    var phiTypeCode = String();
    var phiTypeDesc = String();
}

Filter

var filteredArray = self.modelArray.filter { $0.manufacturer.range(of: manufacturerVar, options: .caseInsensitive) != nil }

This produces the correct filtered Array, only due to the possibility of similar models with different model numbers, I am trying to remove duplicates from filteredArray. Fairly new to swift I don't have a great deal of experience making the struct hashable to be able to use the suggested solutions.

Hopefully this is more clear

Upvotes: 3

Views: 4689

Answers (1)

Glenn Posadas
Glenn Posadas

Reputation: 13283

First off, I tried making a sample in my PlayGround.

  1. Conform your model model to the protocal Equatable, like so:

    struct Car: Equatable {
    
        var modelName = String()
        var manufacturer = String()
    
        init(modelName: String, manufacturer: String) {
            self.modelName = modelName
            self.manufacturer = manufacturer
        }
    
        static func == (lhs: Car, rhs: Car) -> Bool {
            return lhs.modelName == rhs.modelName
        }
    }
    

In the code above, we're assuming that the modelName is the primary key of your model.

  1. Now make a function that enumerates your data source and returns a new data source after checking the element one by one, like so:

    // returns unique array
    
    func unique(cars: [Car]) -> [Car] {
    
        var uniqueCars = [Car]()
    
        for car in cars {
            if !uniqueCars.contains(car) {
                uniqueCars.append(car)
            }
        }
    
        return uniqueCars
    }
    

Finally, you now have the function to generate a new unique data source.

Example:

// Variable

var cars = [Car]()

// Adding data models to data source

let car1 = Car(modelName: "Kia Picanto", manufacturer: "Kia")
let car2 = Car(modelName: "Honda XX", manufacturer: "Honda")
let car3 = Car(modelName: "Honda XX", manufacturer: "Honda")

cars.append(car1)
cars.append(car2)
cars.append(car3)

// Now contains only two elements.
let uniqueCars = unique(cars: cars)

Upvotes: 14

Related Questions