Skip to content

Commit

Permalink
Added Array .unique(keyPath:secondKeyPath:)
Browse files Browse the repository at this point in the history
  • Loading branch information
ddaddy committed Jan 27, 2021
1 parent 56d9a1d commit 4c324c8
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
38 changes: 38 additions & 0 deletions DJSwiftHelpers/Helpers/Array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,42 @@ extension Array {
return alreadyExists ? result : result + [element]
}
}

/**
Filters an array to return one of each item where the combined keyPath elements are unique
- Parameters:
- keyPath: The first keypath to filter
- secondKeyPath: The second keypath to filter
Example:
```
struct Person {
let firstName:String
let surname:String
let age:Int
}
let array = [
Person(firstName: "Darren", surname: "Jones", age: 36),
Person(firstName: "Darren", surname: "Jones", age: 42),
Person(firstName: "Jenny", surname: "Jones", age: 42),
Person(firstName: "Mark", surname: "Chadwick", age: 22)
]
let filtered = array.uniques(by: \.firstName, and: \.surname)
/*
[
{firstName: "Darren", surname: "Jones", age: 36},
{firstName: "Jenny", surname: "Jones", age: 42},
{firstName: "Mark", surname: "Chadwick", age: 22}
]
*/
```
*/
func uniques<T: Hashable, U: Hashable>(by keyPath: KeyPath<Element, T>, and secondKeyPath: KeyPath<Element, U>) -> [Element] {
return reduce([]) { result, element in
let alreadyExists = (result.contains(where: { $0[keyPath: keyPath] == element[keyPath: keyPath] && $0[keyPath: secondKeyPath] == element[keyPath: secondKeyPath] }))
return alreadyExists ? result : result + [element]
}
}
}
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ Example:
.uniques(by: \.surname)
```

Filters an array to return one of each item where the combined keyPath elements are unique

```swift
uniques<T: Hashable, U: Hashable>(by keyPath: KeyPath<Element, T>, and secondKeyPath: KeyPath<Element, U>) -> [Element]

Example:
.uniques(by: \.firstName, and: \.surname)
```

### CLLocationCoordinate2D
Determine if a location is within a bounding rect

Expand Down

0 comments on commit 4c324c8

Please sign in to comment.