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}$