I'm working with the code below, which works well for my purposes; however, instead of the canonical ordering seen in the output, I want the output produced in the order I give in the Cases line of code. Any help is most appreciated.

m = {{N11, "x"}, {N12, "y"}, {N19, "z"}, {N20, "w"}, {N41, 
    "exz"}, {N42, "jy"}, {N49, "br"}, {N50, "mew"}, {N61, "qr"}, {N62,
     "xqe"}, {N539, "ycf"}, {N551, "pyu"}, {N559, "wq"}, {N560, 
Cases[m, {N19 | N560 | N41 | N61 | N551 | N20 | N539, __}];

Output from the above code

N19 z
N20 w
N41 exz
N61 qr
N539 ycf
N551 pyu
N560 hra

2 Answers 2

alternatives = N19 | N560 | N41 | N61 | N551 | N20 | N539;

You can map Cases over the list of alternatives:

Join @@ Cases[{#, __}][m] & /@ (List @@ alternatives);

TableForm @ %

enter image description here

Alternatively, sort the output of Cases by the position in alternatives of the first column elements:

SortBy[PositionIndex[List @@ alternatives]@*First][Cases[m, {alternatives, __}]];

% // TableForm

enter image description here

  • 1
    $\begingroup$ Many many thanks kglr; once again I very much appreciate you sharing your excellent skills! ... v/r ... prg $\endgroup$
    – user42700
    Feb 7, 2021 at 0:34
  • $\begingroup$ @PRG, my pleasure. Thank you for the accept. $\endgroup$
    – kglr
    Feb 7, 2021 at 0:39

The cases will be found in the order they occur in m. If each case is unique, as in the example, the following can be used:

 Cases[m, {N19 | N560 | N41 | N61 | N551 | N20 | N539, __}]
 ][[Ordering[N19 | N560 | N41 | N61 | N551 | N20 | N539]]]
  • $\begingroup$ Michael E2 ... thank u very much!!! $\endgroup$
    – user42700
    Feb 7, 2021 at 15:59
  • $\begingroup$ @PRG You're welcome. :) $\endgroup$
    – Michael E2
    Feb 7, 2021 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.