Skip to content

Instantly share code, notes, and snippets.

@asaaki
Created August 28, 2012 16:10
Show Gist options
  • Save asaaki/3499617 to your computer and use it in GitHub Desktop.
Save asaaki/3499617 to your computer and use it in GitHub Desktop.
Sort an array of keys with an array of order
# input data
sort = [ 3, 1, 4, 2 ]
ary = [ :a, :b, :c, :d ]
# the index value should be in result, too (with id+1 because they can be DB indices)
### sort array represents **position** of item in `ary`
#
# unsorted: 3 => a, 1 => b, 4 => c, 2 => d
# sorted: 1 => b, 2 => d, 3 => a, 4 => b
ary.
map_with_index{|k,i| [i+1, k] }. # in ruby 1.9 can be replaced with `.map.with_index`
zip(sort).
sort_by{|e| e[1] }.
map{|e| e[0] }
### sort array represents **index** of item in `ary`
#
# (index in ary reduced by 1)
# ary map: ary[2] => c, ary[0] => a, ary[3] => d, ary[1] => b
# result: 3 => c, 1 => a, 4 => d, 2 => b
sort.map{ |pos|
[pos] + ary.select{|elem| ary.index(elem) == (pos-1) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment