Last active
December 14, 2020 15:25
-
-
Save Que20/516c756d71914764f495ed809c95b13a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct T { | |
let s: String | |
let v: Int | |
} | |
let a = [T(s: "abc", v: 0), T(s: "abc", v: 1), T(s: "def", v: 0)] | |
let b = Array(a.reduce([Int: [T]]()) { (d, a) -> [Int: [T]] in | |
var d = d | |
let t = a.v | |
d[t] = d[t] == nil ? [a] : d[t]! + [a] | |
return d | |
}.values) // b = [[T(s: "abc", v: 0), T(s: "def", v: 0)], [T(s: "abc", v: 1)]] | |
// As an extension | |
extension Collection { | |
func sortAndChuck<C: Hashable>(keyPath: KeyPath<Element, C>) -> [[Element]] { | |
return Array(self.reduce([C: [Element]]()) { (d, a) -> [C: [Element]] in | |
var d = d | |
let t = a[keyPath: keyPath] | |
d[t] = d[t] == nil ? [a] : d[t]! + [a] | |
return d | |
}.values) | |
} | |
func sortAndChuck2<C: Hashable>(keyPath: KeyPath<Element, C>) -> [[Element]] { | |
var ret: [[Element]] = [] | |
var _v: [C] = [] | |
for t in self { | |
let _tempV = t[keyPath: keyPath] | |
if let i = _v.firstIndex(of: _tempV) { | |
ret[i].append(t) | |
} else { | |
let i: Int = ret.count | |
_v.append(_tempV) // keep index in `_indexRet` | |
ret.insert([], at: i) // init new Array | |
ret[i].append(t) | |
} | |
} | |
return ret | |
} | |
} | |
// Usage : | |
let _ = a.sortAndChuck(keyPath: \T.v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment