How to find Duplicate Elements in Array? I have array of phone numbers so in the phone numbers i should start searching from the right side to the left side and find similar 6 integers. then i should print them out.
相关问题
- How to get the maximum of more than 2 numbers in V
- “Zero out” sensitive String data in Swift
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
- pick a random item from a javascript array
相关文章
- Numpy matrix of coordinates
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- PHP: Can an array have an array as a key in a key-
- How can I vertically align my status bar item text
- Accessing an array element when returning from a f
Feeling ~clever~. Given an array of
Int
sPlease note, this is horrendously efficient for everyone involved, including the compiler, and you.
I'm just showing off.
Edit: lol someone downvoted this, which leads me to reiterate, just in case: please DO NOT USE THIS in production or anywhere else.
I've found a way by using reduce, here is the code(Swift 4):
As a side effect, it returns an array has no dupicated elements.
You can easily modify it for counting duplicated elements numbers, checking string arrays etc.
To filter an array based on properties, you can use this method:
Which you can call as followed, based on the contacts example of Rob:
Same as in @tikhop's answer, but as Array extension (Swift 3):
Antoine's solution in Swift 3+ syntax
To find duplicates, you could build cross reference by phone number, then filter that down to duplicates only. For example, consider:
In Swift 4, you can build the cross reference dictionary with:
Or
Then, to find the duplicates:
Clearly use whatever model types make sense for you, but the above uses the following
Contact
type:There are many, many ways to implement this, so I wouldn't focus on the implementation details of the above, but rather focus on the concept: Build cross reference original array by some key (e.g. phone number) and then filter results down to just those keys with duplicate values.
It sounds like you want to flatten this structure that reflects the duplicates, into a single array of contacts (I'm not sure why you'd want to do that, as you lose the structure identifying which are duplicates of each other), but if you want to do that, you can
flatMap
it:For Swift 2 or 3 renditions, see previous renditions of this answer.