SortBy[Position[B, #]&]@A
{2, 8, 5}
and
SortBy[PositionIndex @ B] @ A (* thanks: WReach *)
{2, 8, 5}
Also,
Cases[Alternatives @@ A] @ B
Select[MatchQ[Alternatives @@ A]] @ B
DeleteCases[Except[Alternatives @@ A]] @ B
Update: Some timing comparisons:
f1[a_, b_] := SortBy[FirstPosition[b, #] &]@a;
f2[a_, b_] := SortBy[Position[b, #] &]@a;
f3[a_, b_] := SortBy[PositionIndex @ b]@a;
f4[a_, b_] := Cases[Alternatives @@ a] @ b;
f5[a_, b_] := Select[MatchQ[Alternatives @@ a]] @ b;
f6[a_, b_] := DeleteCases[Except[Alternatives @@ a]] @b;
funcs = {"f1", "f2", "f3", "f4", "f5", "f6"};
SeedRandom[1]
nb = 10000;
na = 5;
b = RandomSample[Range[10^6], nb];
a = RandomSample[b, na];
t1 = First@RepeatedTiming[r1 = f1[a, b];];
t2 = First@RepeatedTiming[r2 = f2[a, b];];
t3 = First@RepeatedTiming[r3 = f3[a, b];];
t4 = First@RepeatedTiming[r4 = f4[a, b];];
t5 = First@RepeatedTiming[r5 = f5[a, b];];
t6 = First@RepeatedTiming[r6 = f6[a, b];];
r1 == r2 == r3 == r4 == r5 == r6
True
timings = {t1, t2, t3, t4, t5, t6};
Grid[Prepend[SortBy[Last]@Transpose[{funcs, timings}], {"function", "timing"}],
Dividers -> All]
$\begin{array}{|c|c|}
\hline
\text{function} & \text{timing} \\
\hline
\text{f4} & 0.0009 \\
\hline
\text{f6} & 0.0028 \\
\hline
\text{f1} & 0.003 \\
\hline
\text{f2} & 0.0034 \\
\hline
\text{f5} & 0.004 \\
\hline
\text{f3} & 0.012 \\
\hline
\end{array}$
With na = 1000 we get
$\begin{array}{|c|c|}
\hline
\text{function} & \text{timing} \\
\hline
\text{f4} & 0.0014 \\
\hline
\text{f3} & 0.016 \\
\hline
\text{f2} & 0.0737 \\
\hline
\text{f6} & 0.117 \\
\hline
\text{f5} & 0.118 \\
\hline
\text{f1} & 0.59 \\
\hline
\end{array}$
Cases[B, Alternatives@@A]is real-world poetry. – Roman May 04 '19 at 06:12SortBy[A, PositionIndex[B]]– WReach May 04 '19 at 06:38SortByones; the others do not work when there are repeated elements in A – Fortsaint May 04 '19 at 08:44A(and inB),SortBymethods do not work (other methods do work). – kglr May 04 '19 at 09:10A = {5, 2, 8, 5, 8}, B = {9, 2, 6, 8, 5, 1}. TheSortBymethods gives{2, 8, 8, 5, 5}while theCases/Selectmethods gives{2, 8, 5}. Which is right? I still think theSortByare. He needs ".. to arrange the elements in A as given in B.". Deleting duplicates is not rearranging – Fortsaint May 04 '19 at 09:37BisAwith additional elements shuffled. So, for your example modified to makeBhave the same duplications, say,A = {5, 2, 8, 5, 8}; B = {9, 2, 6, 8,5,8, 5, 1} ;we get{2, 8, 8, 5, 5}fromSortBy[PositionIndex@B]@Aand{2, 8, 5, 8, 5}fromCases/Select/DeleteCases. – kglr May 04 '19 at 09:52AssociationinSortBy. It's not in the documentation and looks very useful for future reference. – Roman May 04 '19 at 12:52Bonly has unique elements. I have gone with the following solution:OrderLike[A_List,B_List]:=SortBy[A,FirstPosition[B,#]&];I took out some of the syntactic sugar for us mere mortals. – c186282 May 04 '19 at 16:49