0

I have an issue and need your help. I have array of objects

var arrayDirection: [Directions]

every object has properties:

var name: String?
var uniqueId: Int?

I need find and leave only one object whose values of properties duplicate values of properties of another objects from that array.

For example I print in console:

for object in arrayDirection {
    print(object.name, object.uniqueId)
}

and see:

Optional("name1") Optional(833)

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name4") Optional(833)

Optional("name1") Optional(833)

Optional("name1") Optional(862)

So, I need remove Optional("name1") Optional(833) because there are 3 in array and leave only one as result I'd like to see:

Optional("name1") Optional(833)

Optional("name2") Optional(833)

Optional("name3") Optional(833)

Optional("name1") Optional(862)

4

2 Answers 2

1

Actually you need to remove duplicate from your data set. This link will help what you want to achieve.

However in short, use Set to avoid duplicate data.

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

2 Comments

yes, I understand, but how to do it for several properties?
if this answer is helpful, hope you accept it too. :)
0

You could reduce the array:

let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0.uniqueId == direction.uniqueId }) ? result : result + [direction]
}

Obviously this piece of code assumes that you only want to check if the IDs duplicate, if you want to check whether whole objects duplicate you could either implement the Equatable protocol for your Directions type, or do it like that:

let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0.uniqueId == direction.uniqueId && $0.name == direction.name }) ? result : result + [direction]
}

And with Equatable protocol implemented it gets actually really simple:

let reducedArray: [Direction] = myArray.reduce([]) { result, direction in
   result.contains(where: { $0 == direction }) ? result : result + [direction]
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.