Proposition
Just for fun, here is a version inspired by the DeleteDuplicates
code of Mr.Wizard in this answer,
deleteDuplicates[list1_, list2_] := Module[{f, i = 0, bag = Internal`Bag[{}]},
f[y_] := (i++; f[y] := (Internal`StuffBag[bag, {++i}]; Nothing); y);
{f /@ list1, Delete[list2, Internal`BagPart[bag, All]]}]
For Mathematica versions older than 10.2, Nothing
can be replaced by Unevaluated@Sequence[]
.
Timings
This code is much faster than OP's but is slower than the best solutions by a factor of roughly 3. Considering OP's data
indices = {Prime /@ Range[5000], Prime /@ Range[100, 300]} // Flatten;
values = RandomReal[100, 3] & /@ Range[Length[indices]];
and gathering the solutions posted so far
nikie1[list1_, list2_] := Module[{uniqueIndices = DeleteDuplicates[list1]},
{uniqueIndices, Association[Thread[indices -> values]] /@ uniqueIndices}];
nikie2[list1_, list2_] := Transpose[
GatherBy[Transpose[{list1, list2}], First][[All, 1]]];
chris1[list1_, list2_] := Module[{data = MapThread[List, {list1, list2}]},
Part[data, Sort[Part[Range[Length@data][[#]],
Most@FoldList[Plus, 1, Length /@ Split[data[[All, 1]][[#]]]]]]] &@
Ordering[First /@ data] // Transpose];
chris2[list1_, list2_] :=
Transpose[DeleteDuplicatesBy[MapThread[List, {list1, list2}], First]];
xavier[list1_, list2_] := Module[{f, i = 0, bag = Internal`Bag[{}]},
f[y_] := (i++; f[y] := (Internal`StuffBag[bag, {++i}]; Nothing); y);
{f /@ list1, Delete[list2, Internal`BagPart[bag, All]]}]
I get the following timings on my computer
timings = Through[Map[Composition[AbsoluteTiming, #] &,
{nikie1, nikie2, chris1, chris2, xavier}][indices, values]][[All, 1]];
TableForm[Transpose[{{nikie1, nikie2, chris1, chris2, xavier}, timings}]]