Skip to content

Instantly share code, notes, and snippets.

@zhangqifan
Last active May 14, 2020 14:39
Show Gist options
  • Select an option

  • Save zhangqifan/090b393a7215a4e87e97c499b24b24f7 to your computer and use it in GitHub Desktop.

Select an option

Save zhangqifan/090b393a7215a4e87e97c499b24b24f7 to your computer and use it in GitHub Desktop.
Sorting custom objects array by another array with a specific property in Swift
/// These implementations of sorting based on a specific property of custom object. For example:
/// struct Person {
/// var age: Int
/// var name: String
/// }
///
/// // Case 1:
/// let people = [Person(age: 10, name: "Tom"), Person(age: 12, name: "John"), Person(age: 20, name: "Peter"), Person(age: 1, name: "Nancy")]
/// let orderedPeople = [Person(age: 12, name: "John"), Person(age: 10, name: "Tom")]
///
/// let result = people.reorder(by: orderedPeople, keyPath: \.age))
/// // Prints: [Person(age: 12, name: "John"), Person(age: 10, name: "Tom"), Person(age: 20, name: "Peter"), Person(age: 1, name: "Nancy")]
///
/// // Case 2:
/// let people = the same as above
/// let orderedAges = [12, 10]
///
/// let result = people.reorder(by: orderedAges, keyPath: \.age))
/// // Prints: the same as above
extension Array {
func reorder<T: Equatable>(by orderedArray: [T], keyPath: KeyPath<Element, T>) -> [Element] {
return self.sorted { (lhs, rhs) -> Bool in
guard let aIndex = orderedArray.firstIndex(of: lhs[keyPath: keyPath]) else { return false }
guard let bIndex = orderedArray.firstIndex(of: rhs[keyPath: keyPath]) else { return true }
return aIndex < bIndex
}
}
func reorder<T: Equatable>(by orderedArray: [Element], keyPath: KeyPath<Element, T>) -> [Element] {
let comp = orderedArray.map { e in return e[keyPath: keyPath] }
return self.sorted { (lhs, rhs) -> Bool in
guard let aIndex = comp.firstIndex(of: lhs[keyPath: keyPath]) else { return false }
guard let bIndex = comp.firstIndex(of: rhs[keyPath: keyPath]) else { return true }
return aIndex < bIndex
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment