sort swift array and keep track of original index -


i sort swift array , keep track of original indices. example: arraytosort = [1.2, 5.5, 0.7, 1.3]

indexposition = [0, 1, 2, 3]

sortedarray = [5.5, 1.3, 1.2, 0.7]

indexposition = [1, 3, 0, 2]

is there easy way of doing this?

easiest way enumerate. enumerate gives each element in array index in order appear , can treat them separately.

let sorted = arraytosort.enumerate().sort({$0.element > $1.element}) 

this results in [(.0 1, .1 5.5), (.0 3, .1 1.3), (.0 0, .1 1.2), (.0 2, .1 0.7)]

to indices sorted:

let justindices = sorted.map{$0.index}   // [1, 3, 0, 2] 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -