Sort a list by elements of another list
Permute[list2, FindPermutation[ list2[[All,1]] , list1[[All,1]] ] ]
{{A, 4}, {B, 5}, {C, 1}}
list1 = {{A, 12}, {B, 10}, {C, 4}, {D, 2}};
list2 = {{A, 4}, {D, 11}, {B, 5}, {C, 1}};
idx = Lookup[
AssociationThread[list1[[All, 1]] -> Range[Length[list1]]],
list2[[All, 1]]
];
result = list2;
result[[idx]] = list2;
result
{{A, 4}, {B, 5}, {C, 1}, {D, 11}}
ugly but fast:
list2[[Ordering[list2[[All, 1]]][[Ordering[Ordering[list1[[All, 1]]]]]]]]
{{A, 4}, {B, 5}, {C, 1}}
even faster:
result = list2;
result[[Ordering[list1[[All, 1]]]]] = SortBy[list2, First];
result
{{A, 4}, {B, 5}, {C, 1}}
benchmarks
s = 10^7;
list1 = Transpose[{PermutationList@RandomPermutation[s],
RandomInteger[{0, 10}, s]}];
list2 = Transpose[{PermutationList@RandomPermutation[s],
RandomInteger[{0, 10}, s]}];
(* my first solution *)
result1 = list2[[Ordering[list2[[All, 1]]][[Ordering[Ordering[list1[[All, 1]]]]]]]]; //AbsoluteTiming//First
(* 8.6416 *)
(* my second solution *)
result2 = Module[{L},
L = list2;
L[[Ordering[list1[[All, 1]]]]] = SortBy[list2, First];
L]; //AbsoluteTiming//First
(* 6.89593 *)
(* MikeY's solution *)
result3 = Permute[list2, FindPermutation[list2[[All, 1]], list1[[All, 1]]]]; //AbsoluteTiming//First
(* 15.808 *)
(* Henrik Schumacher's solution *)
result4 = Module[{idx, L},
idx = Lookup[AssociationThread[list1[[All, 1]] -> Range[Length[list1]]], list2[[All, 1]]];
L = list2;
L[[idx]] = list2;
L]; //AbsoluteTiming//First
(* 31.7412 *)
(* make sure all methods agree *)
result1 == result2 == result3 == result4
(* True *)