Skip to content

Instantly share code, notes, and snippets.

@melvitax
Last active July 24, 2017 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melvitax/0321f48b64ae551b6e222668274e05ea to your computer and use it in GitHub Desktop.
Save melvitax/0321f48b64ae551b6e222668274e05ea to your computer and use it in GitHub Desktop.
// Make array from properties of another array
let ids = array.map { $0.id }
// Filter duplicate items from array based on specific properties
extension Array {
func filterDuplicate<T>(_ keyValue:(Element)->T) -> [Element] {
var uniqueKeys = Set<String>()
return filter{uniqueKeys.insert("\(keyValue($0))").inserted}
}
}
let filtered = objectsArray.filterDuplicate{ ($0.name,$0.age) }
// Filter array by property values
let find = items.filter({["value 1", "value 2"].contains($0.propertyName)})
/**
Splits an array into smaller
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print(array.spliyBy(5)) // [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]]
*/
extension Array {
func splitBy(_ chunkSize: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: chunkSize).map {
Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment