# Ordering with repeats

A quick question on list ordering, how can I easily get the ordering of the list, so that, for

{0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]}


I get

{1, 2, 4, 2, 3, 4}


Ordering does not seem to work.

Edit: Thank you for all the wonderful answers. What might be the best way to test which one is the fastest, maybe RepeatedTiming?

list = {0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]}

list /. Union @ Flatten @
MapIndexed[
#1 -> #2[[1]] &,
Split @ SortBy[N] @ list,
{2}]


{1, 2, 4, 2, 3, 4}

Also

With[{x = N @ list},
Flatten @ Replace[x, MapIndexed[Rule] @ Union[x], {1}]]


{1, 2, 4, 2, 3, 4}

• Thanks. Can you compare it with my answer? Is this faster? Feb 17 at 0:30
• With list = Flatten@Table[list, {100000}] my answer is almost twice as fast
– eldo
Feb 17 at 0:39

Using Lookup:

list = {0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]}

a1 = DeleteDuplicates@SortBy[list, N]
rules = Thread[a1 -> Range@Length@a1]
Lookup[rules, list]


Result:

{1, 2, 4, 2, 3, 4}

Just an alternative, combining OrderingBy with DeleteDuplicates

list = {0, Sqrt[3], 2 Sqrt[3], Sqrt[3], 3, 2 Sqrt[3]};

list /. Thread[# -> OrderingBy[#, N]]&@DeleteDuplicates@list


{1, 2, 4, 2, 3, 4}

l = {0, Sqrt[3], 2  Sqrt[3], Sqrt[3], 3, 2  Sqrt[3]};


Using Split, SortBy and Thread:

l /.Rule @@@ Splice@*Thread /@ Thread[{#, Range@Length@#}] &@Split@SortBy[N]@l

(*{1, 2, 4, 2, 3, 4}*)

• But I want the same numbers to correspond to the same ranks. Perhaps ordering is not the word? So 0->1, Sqrt[3]->2, 3->3 and 2 Sqrt[3]-> 4 Feb 17 at 0:00
• @samwolfe Your solution is still faster. Feb 17 at 2:02
rankList[list_] :=
Replace[#, PositionIndex[Sort@DeleteDuplicates@#][[All, 1]], 1] &@
N[list]


seems to do the trick, though I need to use N.