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)

Vadim Nikolaev
  • 2,132
  • 17
  • 34
  • There are several similar Q&As already: https://stackoverflow.com/questions/34709066/remove-duplicate-objects-in-an-array, https://stackoverflow.com/questions/42304150/remove-duplicated-in-a-struct-array, https://stackoverflow.com/questions/25738817/does-there-exist-within-swifts-api-an-easy-way-to-remove-duplicate-elements-fro – Martin R Jun 07 '17 at 18:56
  • I saw it, but I need compare two different properties – Vadim Nikolaev Jun 07 '17 at 18:58
  • 1
    Here is another one: https://stackoverflow.com/questions/38153674/remove-duplicate-structs-in-array-based-on-struct-property-in-swift – All the solutions can be used for types with arbitrary many properties. – Martin R Jun 07 '17 at 19:00
  • @MartinR great! It's working as must, thank you for the last link – Vadim Nikolaev Jun 07 '17 at 19:05

2 Answers2

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.

elk_cloner
  • 2,049
  • 1
  • 12
  • 13
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]
}
user3581248
  • 964
  • 10
  • 22