ios - How to sort 1 array in Swift / Xcode and reorder multiple other arrays by the same keys changes -
sorry complex wording of question. main experience php , has command called array_multisort. syntax below:
bool array_multisort ( array &$array1 [, mixed $array1_sort_order = sort_asc [, mixed $array1_sort_flags = sort_regular [, mixed $... ]]] )
it lets sort 1 array , reorder multiple other arrays based on key changes in original.
is there equivalent command in swift / xcode 7.2?
i have have set of arrays:
firstname age city country active
active array of time in seconds user has been active within app. order descending or ascending , other arrays change remain consistent.
you create array of indexes in sorted order , use mapping:
var names = [ "paul", "john", "david" ] var ages = [ 35, 42, 27 ] let neworder = names.enumerate().sort({$0.1<$1.1}).map({$0.0}) names = neworder.map({names[$0]}) ages = neworder.map({ages[$0]})
[edit] here's improvement on technique :
it's same approach sorting , assignment in 1 step. (can reassigned original arrays or separate ones)
(firstnames,ages,cities,countries,actives) = {( $0.map{firstnames[$0]}, $0.map{ages[$0]}, $0.map{cities[$0]}, $0.map{countries[$0]}, $0.map{actives[$0]} )} (firstnames.enumerated().sorted{$0.1<$1.1}.map{$0.0})
[edit2] , array extension make easier use if sorting in place:
extension array element:comparable { func ordering(by order:(element,element)->bool) -> [int] { return self.enumerated().sorted{order($0.1,$1.1)}.map{$0.0} } } extension array { func reorder<t>(_ otherarray:inout [t]) -> [element] { otherarray = self.map{otherarray[$0 as! int]} return self } } firstnames.ordering(by: <) .reorder(&firstnames) .reorder(&ages) .reorder(&cities) .reorder(&countries) .reorder(&actives)
combining previous two:
extension array { func reordered<t>(_ otherarray:[t]) -> [t] { return self.map{otherarray[$0 as! int]} } } (firstnames,ages,cities,countries,actives) = {( $0.reordered(firstnames), $0.reordered(ages), $0.reordered(cities), $0.reordered(countries), $0.reordered(actives) )} (firstnames.ordering(by:<))
Comments
Post a Comment