# Sort an array according other array

I am trying to sort an array according other array. More specifically, sort ε_ according Z.

NN = 6
Z = rand(NN)
ε_= rand(NN)
teste = [ Z[sortperm(Z)] ε_[sortperm(ε_)] ]
test_f(Z) = teste[teste[:,1] .== Z , 2]
ε_ = test_f.(Z)

I believe there is a solution in fewer lines.

`first.(sort(collect(zip(ε_,Z)),by=last))`

1 Like

You mean?

`ε_ .= ε_[sortperm(Z)]`

1 Like

No. It is the same that

ε_[ sortperm(Z) , :]

But my goal is different. You can run my script and will see that it is not the same goal.

No. my goal is different. You can run my script and will see that it is not the same goal.

Picking easier to read random things, I think this is a less convoluted way to get the same answer:

``````julia> Z = rand(Int8, 6); println(Z)
Int8[68, -64, -110, 95, -116, 81]

julia> ε_ = rand('a':'z', 6); println(ε_)
['i', 'b', 'u', 'k', 'v', 'j']

julia> teste = [ Z[sortperm(Z)] ε_[sortperm(ε_)] ]
6×2 Matrix{Any}:
-116  'b'
-110  'i'
-64  'j'
68  'k'
81  'u'
95  'v'

julia> test_f(Z) = teste[teste[:,1] .== Z , 2]
test_f (generic function with 1 method)

julia> test_f.(Z)  # desired result?
6-element Vector{Vector{Any}}:
['k']
['j']
['i']
['v']
['b']
['u']

julia> ε_[sortperm(Z)] |> println  # "sort an array according other array"
['v', 'u', 'b', 'i', 'j', 'k']

julia> sort(ε_)[invperm(sortperm(Z))] |> println  # more direct way?
['k', 'j', 'i', 'v', 'b', 'u']
``````
2 Likes

Similar result but different output array type, just in case:

``````test_f2(Z) = teste[indexin(Z,teste[:,1]),2]
test_f2(Z)

6-element Vector{Any}:
'k': ASCII/Unicode U+006B (category Ll: Letter, lowercase)
'j': ASCII/Unicode U+006A (category Ll: Letter, lowercase)
'i': ASCII/Unicode U+0069 (category Ll: Letter, lowercase)
'v': ASCII/Unicode U+0076 (category Ll: Letter, lowercase)
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
'u': ASCII/Unicode U+0075 (category Ll: Letter, lowercase)
``````
1 Like